打开时PHP Zip文件下载错误

时间:2013-11-13 20:11:58

标签: php file download zip

我需要从网站下载一个zip文件,因为我要求在一个下载(最多100个单独的文件)中合并多个文件。

尝试创建zip文件时,按预期下载,文件名也按照预期以“YYYY.MM.DD - HH.MM.SS”格式显示。尝试在Windows 7 (或winzip)中打开zip文件时出现问题 - 我收到以下错误消息。多次尝试反复发生这种情况。

我认为我在编写zip文件的创建或下载时遇到了错误,而不是zip文件格式本身就是一个问题因为我可以打开不同的zip文件 - 任何人都可以看到我可能犯的错误吗? (错误图片下方的代码)

我尝试使用Download multiple files as a zip-file using php作为参考。

//backup file name based on current date and time
$filename = date("Y.m.j - H.i.s");
//name of zip file used when downloading
$zipname = 'temp.zip';
//create new zip file
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
//yes, I know the zip file is empty currently - I've cut the code from here for
//now as the zip file doesn't function with / without it currently
$zip->close();

//download file from temporary file on server as '$filename.zip'
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$filename.'.zip');
header('Content-Length: ' . filesize($zipname));
readfile($zipname);

3 个答案:

答案 0 :(得分:2)

检查Web服务器用户是否具有您正在创建ZIP文件的文件夹的写入权限。尽管有文档,如果无法创建ZIP文件,ZipArchive::open()将无声地失败并返回true(即成功)。此外,ZipArchive::addFile()似乎会根据您的意愿为这个不存在的存档添加任意数量的文件,也不会报告错误。出现错误的第一个点是ZipArchive :: close()返回“false”。错误日志中也不会显示任何错误消息。

Readfile() 向日志报告错误并失败,因此结果是本地硬盘上的零长度ZIP文件。

原因似乎是ZipArchive类只是在内存中组装一个文件列表,直到它关闭,此时它将所有文件组装到Zip文件中。如果无法执行此操作,则ZipArchive::close()会返回false

注意:如果zip文件为空,则可能根本不创建!您的下载将继续,但readfile()将失败,您将获得一个零长度的ZIP文件下载。

怎么做?

在您的代码中添加一些错误检查以报告其中一些内容:

$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);

// Add your files here

if ($zip->close() === false) {
   exit("Error creating ZIP file");
};


//download file from temporary file on server as '$filename.zip'
if (file_exists($zipname)) {

    header('Content-Type: application/zip');
    header('Content-disposition: attachment; filename='.$filename.'.zip');
    header('Content-Length: ' . filesize($zipname));
    readfile($zipname);
} else {
    exit("Could not find Zip file to download");
}

答案 1 :(得分:2)

我遇到了这个问题,但这个解决方案为我解决了

Add ob_clean(); just before your new output headers.

我使用的是旧版本的 Silverstripe 并且我的 zip 文件不断被损坏,即使数据在那里是可见的。

解决上面这个晦涩的注释使用ob_clean();很有帮助,我想把它拿出来作为这个问题的答案。

来自 PHP 文档:
ob_clean(); 丢弃输出缓冲区的内容。

ob_clean(); 不会像 ob_end_clean() 那样破坏输出缓冲区。

答案 2 :(得分:0)

尝试使用文本编辑器打开zip文件。 这样你就可以检查代码中是否有php错误(在压缩步骤中)。

相关问题