如何在php中压缩.zip文件后下载该文件


how to download a .zip file after it has been compressed in php

我用一个函数压缩了一个文件夹,文件(compressed.zip)包含了该文件夹的所有内容。我测试了下载,一切都很好。现在我想在压缩完成后自动下载文件。

这是我用来做这件事的代码:

if(isset($_GET['compress'])) {
            // compress folder and sent compressed zip to plugins/sfm/views
            Zip($_GET['compress'], "plugins/sfm/views/compressed.zip");
            if(file_exists('plugins/sfm/views/compressed.zip')){
            // set example variables
            $filename = "compressed.zip";
            $filepath = "plugins/sfm/views/";
            // http headers for zip downloads
            header("Pragma: public");
            header("Expires: 0");
            header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
            header("Cache-Control: public");
            header("Content-Description: File Transfer");
            header("Content-type: application/octet-stream");
            header("Content-Disposition: attachment; filename='"".$filename."'"");
            header("Content-Transfer-Encoding: binary");
            header("Content-Length: ".filesize($filepath.$filename));
            ob_end_flush();
            @readfile($filepath.$filename);
            }

        }

就像我说的;当我通过url访问plugins/sfm/views/compressed.zip时,他可以毫无问题地提取文件夹,并且所有内容都在其中。但强制下载给了我一个压缩的.zip,似乎已经损坏了。

当试图用Winrar打开下载时,他说:档案意外结束。和:档案要么格式未知,要么已损坏。为什么强制下载会给我这个错误?zip文件压缩正确!

这似乎解决了问题:

//clean all levels of output buffering
while (ob_get_level()) {
ob_end_clean();
}

@readfile($filepath.$filename); 之前