【发布时间】:2011-09-19 12:22:12
【问题描述】:
我用 php zip (http://php.net/manual/de/book.zip.php) 创建了一个 zip 文件
现在我必须将它发送到浏览器/强制下载。
【问题讨论】:
标签: php zip force-download
我用 php zip (http://php.net/manual/de/book.zip.php) 创建了一个 zip 文件
现在我必须将它发送到浏览器/强制下载。
【问题讨论】:
标签: php zip force-download
<?php
// or however you get the path
$yourfile = "/path/to/some_file.zip";
$file_name = basename($yourfile);
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=$file_name");
header("Content-Length: " . filesize($yourfile));
readfile($yourfile);
exit;
?>
【讨论】:
设置 content-type、content-length 和 content-disposition 头,然后输出文件。
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="'.$filename.'"');
header('Content-Length: '.filesize($filepath) );
readfile($filepath);
设置Content-Disposition: attachment会建议浏览器下载文件而不是直接显示。
【讨论】:
如果您的 ZIP 已经在服务器上,并且如果 Apache 可以通过 HTTP 或 HTTPS 访问此 ZIP,那么您应该重定向到该文件,而不是使用 PHP“读取它”。
效率更高,因为您不使用 PHP,所以不需要 CPU 或 RAM,而且会下载速度更快 >,因为也不需要PHP读/写,只需要直接下载。 让 Apache 完成这项工作!
所以一个不错的功能可能是:
if($is_reachable){
$file = $relative_path . $filename; // Or $full_http_link
header('Location: '.$file, true, 302);
}
if(!$is_reachable){
$file = $relative_path . $filename; // Or $absolute_path.$filename
$size = filesize($filename); // The way to avoid corrupted ZIP
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename=' . $filename);
header('Content-Length: ' . $size);
// Clean before! In order to avoid 500 error
ob_end_clean();
flush();
readfile($file);
}
exit(); // Or not, depending on what you need
我希望它会有所帮助。
【讨论】:
$is_reachable 来自哪里...?
你需要这样做,否则你的zip会损坏:
$size = filesize($yourfile);
header("Content-Length: \".$size.\"");
所以 content-length 头需要一个真实的字符串,而文件大小返回和整数。
【讨论】: