我正在尝试将图像添加到zip文件并强制使用标题来下载它。以下是我现在正在使用的代码片段。
$zip = new ZipArchive();
$zip_name = 'design_images_'.time() .".zip";
if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE){
$error .= "* Sorry ZIP creation failed at this time";
}
$i = 0;
foreach($valid_files as $file){
$image_name = 'design_image_' . $i;
$zip->addFile($file, $image_name);
$i++;
}
$zip->close();
if(file_exists($zip_name)){
// force to download the zip
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="'.$zip_name.'"');
readfile($zip_name);
}
当我尝试打开zip文件时,它会出错:存档已损坏。
答案 0 :(得分:0)
在提供下载之前尝试清理输出缓冲区:
if(file_exists($zip_name)){
// Clean the output buffer.
while (ob_get_level()) {
ob_end_clean();
}
// force to download the zip
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="'.$zip_name.'"');
readfile($zip_name);
}