如何防止 Zip 文件在流式传输时损坏


How to keep a Zip file from becoming corrupted when streamed

我在流式传输 Zip 文件以供使用 PHP 下载时遇到问题。 这是我的代码:

$arrFiles = $this->getRequest()->getPost('files', array());
$objFacultyClubDownloads = new FacultyClub_Downloads();
$objFCDownloads = $objFacultyClubDownloads->saveFacultyClubDownloadsInfo($arrFiles);
// create the zip file
 $strZipName = 'download' . time() . '.zip';
 $strZipSavePath = PUBLIC_PATH . '/downloads/temp/';
 $objZip = new ZipArchive;
 if ($objZip->open($strZipSavePath . $strZipName, ZipArchive::CREATE) === TRUE) {
 foreach ($arrFiles['file_name'] as $intKey => $strValue) {
     $strFilePath = PUBLIC_PATH . $strValue;
     if (file_exists($strFilePath)) {
         $strFileName = strtolower(basename($strValue));
         $objZip->addFile($strFilePath, $strFileName);
      }
  }
   $strZipName = $objZip->filename;
   $objZip->close();
}
// strip out the layout and view
$this->getHelper('layout')->disableLayout();
$this->getHelper('viewRenderer')->setNoRender();
 // stream the zip file
 header('Content-Type: application/zip');
 header("Content-Disposition: attachment; filename=Faculty-Club-Download.zip");
 //header('Content-Length: ' . filesize($strZipName));
 readfile($strZipName);

这是在Zend Framework中。 问题似乎是流媒体。 下载是在临时文件夹中正确创建的。 我可以很好地解压缩该 Zip。 但是,当文件流式传输以供下载时,它会解压缩扩展名为 .cpgz 的文件。 从我正在阅读的内容来看,这意味着 Zip 已损坏。 当我双击它解压缩它时,我只是得到了扩展名为 .cpgz 的同一文件的另一个版本——它会复制自己。

我尝试在readfile之前添加ob_cleanflush,但这没有帮助。 知道这里发生了什么吗?

如果服务器上的文件有效,但是在通过http传输时损坏,我会查看PHP和浏览器之间的所有内容。 假设您使用的是 Apache,请从那里开始并为此请求禁用 gzip。 我们在反向代理和双重压缩方面遇到了类似的问题。

可能必须在PHP代码的早期调用它:

apache_setenv('no-gzip', '1');

http://php.net/apache_setenv