[英]PHP Zip is downloaded empty
在我的网站上,用户将能够下载ZIP格式的多个文件。 问题是zip->close()
删除了我在foreach
循环中添加的所有文件。
这是代码:
foreach ($file_name_list as $file_name) {
var_dump($zip);
echo '<br>';
$zip->addFile($files_path . $file_name, $file_name);
}
var_dump($zip);
echo '<br>';
$zip->close();
echo '<br>';
echo 'After closing:<br>';
var_dump($zip);
echo '<br>';
输出是:
object(ZipArchive)#4 (5) { ["status"]=> int(0) ["statusSys"]=> int(0) ["numFiles"]=> int(0) ["filename"]=> string(29) "/var/www/html/files/tests.zip" ["comment"]=> string(0) "" }
object(ZipArchive)#4 (5) { ["status"]=> int(0) ["statusSys"]=> int(0) ["numFiles"]=> int(1) ["filename"]=> string(29) "/var/www/html/files/tests.zip" ["comment"]=> string(0) "" }
object(ZipArchive)#4 (5) { ["status"]=> int(0) ["statusSys"]=> int(0) ["numFiles"]=> int(2) ["filename"]=> string(29) "/var/www/html/files/tests.zip" ["comment"]=> string(0) "" }
Afterclosing:
object(ZipArchive)#4 (5) { ["status"]=> int(0) ["statusSys"]=> int(0) ["numFiles"]=> int(0) ["filename"]=> string(0) "" ["comment"]=> string(0) "" }
如您所见,当PHP运行zip->close()
它将删除添加的文件。 它还会删除文件名。 我不知道出什么问题了,因为它可以在Windows本地计算机上正常运行,但不能在服务器上的Ubuntu虚拟机上运行。
如何解决?
我真的需要zip->close()
吗? 我只想下载文件,无论如何。
我自己找到了答案。
问题是,通过zip->open($zipname, ZipArchive::CREATE)
zip时zip->open($zipname, ZipArchive::CREATE)
必须使用zip的完整路径,而不是zip名称。 我认为另一个问题是该zip的创建权限很少,因此无法下载。
起作用的代码:
function donwloadFilesInZip($array) {
$filesName = $array['files'];
$filesPath = rtrim($array['filesDir'], '/');
$zipName = $array['zipname'];
$zipPath = "$filesPath/$zipName";
$zip = new ZipArchive();
if($zip->open($zipPath, ZipArchive::CREATE)) {
foreach ($filesName as $fileName) {
if(file_exists("$filesPath/$fileName")) {
$zip->addFile("$filesPath/$fileName", $fileName);
}
}
$zip->close();
#file permissions
chmod($zipPath, 777);
#headers
header('Content-type: application/zip');
header("Content-Disposition: attachment; filename=$zipName");
header('Content-length: ' . filesize($zipPath));
#refresh the file permissions in order to read it
ob_clean();
flush();
#download
readfile($zipPath);
#delete
unlink($zipPath);
} else {
#display some error message here
}
}
旧代码(在我的Windows本地计算机上运行良好,但在Ubuntu中效果不佳):
function donwload_files_in_zip($array) {
$file_name_list = $array['files_list'];
$zip_name = $array['zipname'];
$files_path = $array['files_path'];
$zip = new ZipArchive();
$zip->open($zip_name, ZipArchive::CREATE);
foreach ($file_name_list as $file_name) {
$zip->addFile($files_path . $file_name, $file_name);
}
$zip->close();
// headers
header('Content-Type: application/zip');
header("Content-disposition: attachment; filename = $zip_name");
header('Content-Length: ' . filesize($zip_name));
// download
readfile($zip_name);
// delete
unlink($zip_name);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.