我正在创建有助于在提取或查看之前锁定 zip 的功能。在 StackOverflow 上所有与 zip 密码相关的线程的帮助下,我无法实现此输出。
从我的角度来看,我认为它是正确的。但是我无法理解的错误是什么以及为什么代码不起作用。低于我正在尝试的 - 请帮助我解决这个问题。
$dir = './';
$zip_file = 'file.zip';
// Get real path for our folder
$rootPath = realpath($dir);
// Initialize archive object
$zip = new ZipArchive();
$zip->open($zip_file, ZipArchive::CREATE | ZipArchive::OVERWRITE);
$zip->setPassword('MY_PASSWORD');
// Create recursive directory iterator
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($rootPath),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file) {
//Skip directories (they would be added automatically)
if (!$file->isDir()) {
// Get real and relative path for current file
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);
// Add current file to archive
$zip->addFile($filePath, $relativePath);
}
}
$zip->setEncryptionName($zip_file, ZipArchive::EM_AES_256); //encrypt it
// Zip archive will be created only after closing object
$zip->close();
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($zip_file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($zip_file));
readfile($zip_file);