在 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 时,他毫无问题地提取了文件夹,并且所有内容都在其中并提取了。
但是强制下载给我的 compressed.zip 似乎已损坏。
当试图用 Winrar 打开下载时,他说:压缩文件意外结束。并且:存档格式未知或已损坏。
为什么强制下载给我这个错误? zip 文件已正确压缩!
这似乎解决了问题:
//clean all levels of output buffering
while (ob_get_level()) {
ob_end_clean();
}
在@readfile($filepath.$filename);
之前
我用函数压缩了一个文件夹,文件 (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 时,他毫无问题地提取了文件夹,并且所有内容都在其中并提取了。 但是强制下载给我的 compressed.zip 似乎已损坏。
当试图用 Winrar 打开下载时,他说:压缩文件意外结束。并且:存档格式未知或已损坏。 为什么强制下载给我这个错误? zip 文件已正确压缩!
这似乎解决了问题:
//clean all levels of output buffering
while (ob_get_level()) {
ob_end_clean();
}
在@readfile($filepath.$filename);