![](/img/trans.png)
[英]How to create a password protected zip file on ftp server using php
[英]PHP 7.2: How to create password protected zip using PHP 7.2
誰能建議我們如何在 php 7.2 中創建受密碼保護的 zip
$zip = new \ZipArchive();
//now working in php 7.2"
$zip->setPassword($password);
//also this is not creating protected zip
$zip->setEncryptionName($filename, ZipArchive::EM_AES_256, $password);
從 PHP 7.2 開始,您應該能夠使用setEncryptionName
將每個文件的密碼作為第三個參數進行加密,或者,如果之前調用了setPassword
,則可以省略它並使用默認密碼。
直接從文檔:
從 PHP 7.2.0 和 libzip 1.2.0 開始,密碼用於解壓縮檔案,也是 ZipArchive::setEncryptionName() 和 ZipArchive::setEncryptionIndex() 的默認密碼。 以前,此功能只設置用於解壓存檔的密碼; 它沒有將不受密碼保護的 ZipArchive 變成受密碼保護的 ZipArchive。
下面的代碼實現了上面提到的兩種情況。 (有趣的是,我的 7-Zip 在打開這個文件時,似乎“記住”了上次輸入的密碼,所以在我重新打開文件之前它不會讓我同時嘗試這兩個密碼,但我認為這是 7-壓縮。)
$zip = new ZipArchive;
if (!$zip->open('test.zip', ZipArchive::CREATE)) {
die('Could not create zip file');
}
// Set the shared/default password
$zip->setPassword('cheese');
// Add a file with the default password
$zip->addFromString('test-1.txt', 'this is file one');
$zip->setEncryptionName('test-1.txt', ZipArchive::EM_AES_256);
// Add a file with a custom password
$zip->addFromString('test-2.txt', 'this is file two');
$zip->setEncryptionName('test-2.txt', ZipArchive::EM_AES_256, 'custom password');
$zip->close();
我已經以許多不同的方式嘗試過它,但它在 linux 下使用 PHP 8.0 對我不起作用。 我已經在 2 個不同的 linux 服務器上進行了嘗試。 安裝了 Libzip 並使用了推薦的版本。
最后,我使用了許多其他開發人員推薦的另一種方式:
<?php
$password = 'get the password by some secure way';
$zipFileName = sprintf('compressed_file--%s-%s.zip', (new DateTime('now'))->format('Y-m-d'), mt_rand(0, 99999));
$zipFilePath = sys_get_temp_dir() . '/' . $zipFileName;
$contentFilePath = 'some_file_prepared_in_tmp_folder.xls';
system('cd /tmp; zip -P ' . $password . ' ' . $zipFilePath . ' ' . $contentFilePath);
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.