【问题标题】:send zip file to browser / force direct download将 zip 文件发送到浏览器/强制直接下载
【发布时间】:2011-09-19 12:22:12
【问题描述】:

我用 php zip (http://php.net/manual/de/book.zip.php) 创建了一个 zip 文件

现在我必须将它发送到浏览器/强制下载。

【问题讨论】:

标签: php zip force-download


【解决方案1】:
<?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;
?>

【讨论】:

  • 为什么我将其视为内嵌内容,却没有提示我下载?
  • @jj 我没有使用文档开头的代码!
  • 是否在所有操作系统(特别是 windows)和浏览器中测试过?
  • exit 对于测试目的是不好的做法。确保您的脚本完成,但不要使用退出。它还将结束任何 phpunit 测试,并且无法恢复...
【解决方案2】:

设置 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会建议浏览器下载文件而不是直接显示。

【讨论】:

  • 这是否意味着对于大型下载文件通过 php 服务器传输?
【解决方案3】:

如果您的 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

我希望它会有所帮助。

【讨论】:

  • ob_end_clean();
  • $is_reachable 来自哪里...?
  • 你好安德烈。从你想要的地方!它可以是您自己的测试,具体取决于您的代码是如何编写的。例如,如果您现在 ZIP 已经存在(例如因为您不必生成它)并且可以通过直接链接访问(无需授权)。继续:如果您可以使用直接链接下载 ZIP,则可以访问,如果不是(身份验证、陌生链接或其他),则需要使用 PHP“强制”下载。
【解决方案4】:

你需要这样做,否则你的zip会损坏:

$size = filesize($yourfile);
header("Content-Length: \".$size.\"");

所以 content-length 头需要一个真实的字符串,而文件大小返回和整数。

【讨论】:

  • 感谢您的评论,因为我使用的是 header('Content-Length: '.filesize($filepath));您的解决方案效果更好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-04
  • 2011-09-25
  • 2011-12-19
  • 2012-07-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多