发送zip文件到浏览器/强制直接下载

Mar*_*uwa 14 php zip force-download

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

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

Amb*_*ber 36

<?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;
?>
Run Code Online (Sandbox Code Playgroud)


XDj*_*juj 7

如果您的 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
Run Code Online (Sandbox Code Playgroud)

我希望它会有所帮助。


Kai*_*aja 5

设置content-type,content-length和content-disposition标头,然后输出文件.

header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="'.$filename.'"');
header('Content-Length: '.filesize($filepath) );
readfile($filepath);
Run Code Online (Sandbox Code Playgroud)

设置Content-Disposition: attachment将建议浏览器下载文件而不是直接显示它.