I wrote a method with PHP in my Symfony project using ZipArchive()
where I want to set password for my zip file.
It's packing the folder with a lot of files so and unfortunately it is unzipping file without requesting password.
I tried it in a simple Zip method and it works, in reference to this link:
I think problem occurs because this method is using RecursiveIteratorIterator
.
My method:
private function zipFolder($source, $destination, $password = null) {
//try it
$password = 'fdgsrhds565eter543';
if (!extension_loaded('zip') || !file_exists($source)) {
throw new Exception('File does not exist.');
}
$zip = new ZipArchive();
if ($zip->open($destination, ZipArchive::CREATE | ZipArchive::OVERWRITE) === true) {
$source = str_replace('\\', '/', realpath($source));
if (is_dir($source) === true) {
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($source, 0),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($files as $file) {
$file = str_replace('\\', '/', $file);
if (in_array(substr($file, strrpos($file, '/') +1), array('.', '..'))) {
continue;
}
$file = realpath($file);
if (is_dir($file) === true) {
$zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
} elseif (is_file($file) === true) {
$zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
}
}
}
} elseif (is_file($source) === true) {
$zip->addFromString(basename($source), file_get_contents($source));
}
if (!empty($password)) {
$zip->setEncryptionName(basename($source), ZipArchive::EM_AES_256, $password);
}
$zip->close();
}
Base name of the source folder is 'latest' and in my zip file, main folder is called latest_backup. Could this be an issue?
source https://stackoverflow.com/questions/67936663/php-zip-with-password-and-setencryptionname-method
No comments:
Post a Comment