通过浏览器下载后,无法解压缩用PHP创建的文件


Unable to unzip file created in PHP after downloading it through a browser

    $zip = new ZipArchive();
    $filename = $first_name . ".zip";
    if ($zip->open($filename, ZipArchive::CREATE)!==TRUE) {
        exit("cannot open <$filename>'n");
    }
    $zip->addFile($first_name . ".clean");
    $zip->addFile($first_name . ".log");
    $zip->addFile($first_name . ".result");
    $zip->addFile($first_name . ".txt");
    $zip->close();
    header("Content-type: application/octet-stream"); 
    header("Content-Disposition: attachment; filename=$filename");
    header("Content-length: " . filesize($filename));
    header("Expires: 0"); 
    header("Pragma: public");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header('Cache-Control: max-age=0'); // no cache
    header("Content-Transfer-Encoding: binary");
    ob_end_flush();
    readfile("$filename");

我试图通过PHP代码创建一个.zip文件,并通过浏览器将其下载到localhost上。下载的zip无法解压缩,并给出如下错误消息:

存档:upload_pnt-prs.zip找不到中心目录签名的末尾。要么这个文件不是一个zip文件,或者它构成了一个多部分归档的一个磁盘。在在后一种情况下,中心目录和zipfile注释将在此存档的最后一个磁盘。unzip:在upload_pnt-prs.zip或upload_pnt-prs.zip.zip,找不到upload_pnt-prs.zip,句点。

我已经尝试了一些已经得到答案的解决方案,但这并不能解决我的问题。请帮忙…

也许您应该重新排列标题序列。我尝试了下面的代码,它工作

header('Pragma: public');   // required
header('Expires: 0');       // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Last-Modified: '.gmdate ('D, d M Y H:i:s', filemtime ($filename)).' GMT');
header('Cache-Control: private',false);
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="'.$filename.'"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.filesize($filename)); // provide file size
header('Connection: close');
readfile($filename);
exit();

希望这将对您有用