我正在使用 phps ZipArchive 类来创建目录的 zip 文件。该代码适用于几乎所有目录,除了两个恰好是最大的目录(最大的目录当前包含 51 个文件,总计 175MB)。当我为这些目录运行代码时,将创建一个大小为 67,108,864 字节的临时文件('filename.zip.[RandomLettersAndNumbers]',例如'filename.zip.riaab4'),脚本会引发内部服务器错误(500)。
到目前为止我已经尝试过的(大部分在源代码中仍然可见):
- 增加
memory_limit
- 增加
max_execution_time
- 查看php错误日志:错误日志为空
- 尝试找到发生错误的确切行:代码执行到
$zip_archive->close();
来源:
//Temporary (debugging) START
ini_set("log_errors", 1);
ini_set("error_log", "php-error.log");
error_log("Hello errors.");
ini_set('memory_limit','512M');
set_time_limit(180);
//phpinfo();
//Temporary (debugging) END
//Get selected directory
// --> Code removed
$result['directory'] = 'directory1';
//Create .zip file
$zip_archive = new ZipArchive();
$ZIP = 'files/'.$result['directory'].'.zip';
if($zip_archive->open($ZIP, ZipArchive::CREATE | ZIPARCHIVE::OVERWRITE) !== TRUE) {
echo 'Error! Error while creating ZIP Archive.';
die;
}
foreach(new DirectoryIterator('files/'.$result['directory']) as $fileInfo) {
if($fileInfo->isDot())
continue;
if(file_exists($fileInfo->getPath()))
$zip_archive->addFile('files/'.$result['directory'].'/'.$fileInfo->getFilename(), $fileInfo->getFilename());
}
//Temporary (debugging) START
echo '<br><br><br>';
var_dump($zip_archive->close());
// ## The following lines are not executed!! ##
echo '<br><br><br>';
var_dump($zip_archive->getStatusString());
echo '<br><br><br>';
//Temporary (debugging) END
if($zip_archive->numFiles > 0 && $zip_archive->close() == true)
$FILE = $ZIP;
else {
}
我错过了什么吗?如果还有什么我可以尝试的,请告诉我。谢谢。
编辑:我有一个更具体的问题:为什么受影响目录的临时 zip 文件的文件大小都是 67,108,864 字节?这与 php/服务器设置的最大文件大小有关,还是可以用 zip 标准/ZipArchive 类来解释?
最佳答案
尝试关闭 ZIP 存档,并在每 5 个左右的文件添加到存档后重新打开它。我假设此解决方案解决了内存限制问题。
此解决方案归功于 MatthewS。
关于PHP:使用 ZipArchive 创建 zip 文件时出错 (500),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34727386/