【发布时间】:2013-11-13 20:11:58
【问题描述】:
我需要从网站下载一个 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);
【问题讨论】:
-
您是否查看过使用 HEX 编辑器获得的 ZIP 文件?如果不是,请告诉我们前四个字节是什么。
-
请同时显示示例内容的添加。到目前为止,您的代码看起来还不错
-
我怀疑以下两个原因之一。
a)发生一些 PHP 错误并打印到标准输出,因此它包含在 ZIP 文件中(当然,它已损坏,因为其中不应该有来自 PHP 错误的随机字符:D)。b)由于 mod_deflate 或类似的原因,PHP 或网络服务器在其上添加了另一层 GZIP。但是,标头不尊重这一点,因此 ZIP 文件不会被浏览器“解压缩”,因此已损坏。 -
我花了很长时间寻找与图像文件类似的问题。我的解决方案是在开始输出新标头之前立即添加
ob_clean();。 -
@Mike W:你是个特别棒的人。我希望我早点知道这一点。有一次,在将服务器升级到 Ubuntu 13.10 后,这对我来说成了一个问题。使用
ob_clean(),最终的 zip 文件会变大大约 10kb,并且可以正常工作。我不知道为什么。但我现在可以忘记它了。