[英]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.