Can anyone suggest how can we create password protected zip in php 7.2
$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);
As of PHP 7.2, you should be able to use setEncryptionName
to encrypt with a per-file password as the third argument, or, if setPassword
was called previously, it can be omitted and the default password can be used.
Directly from the documentation :
As of PHP 7.2.0 and libzip 1.2.0 the password is used to decompress the archive, and is also the default password for ZipArchive::setEncryptionName() and ZipArchive::setEncryptionIndex(). Formerly, this function only set the password to be used to decompress the archive; it did not turn a non-password-protected ZipArchive into a password-protected ZipArchive.
The code below does both scenarios mentioned above. (Interestingly enough, my 7-Zip, when opening this file, appears to "remember" the last password entered so it won't let me try both until I re-open the file, but I think that is a bug in 7-Zip.)
$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();
I have tried it in many different ways but it didn't work for me under linux using PHP 8.0. I have tried it on 2 different linux servers. Libzip is installed and the recommended version is used.
At the end I used the other way that is recommended by many other developers:
<?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);
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.