如何使用PHP强制下载文件?

3

当用户点击“下载此文件”链接时,我希望用户能够下载文件。

使用场景:用户单击链接后,Web应用程序将生成一个文件并将其作为下载“推送”。

以下是我的PHP代码。尽管服务器上的文件正确生成,但它没有被下载(也没有显示下载对话框)。

header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$filename."\"");
header("Content-Transfer-Encoding: binary");
readfile('file.zip');

我试图添加以下内容,但它没有起作用:
header("Location: file.zip");  // not working

虽然我找到了一个JavaScript解决方案(可行),通过尝试以下重定向:

window.location.href = 'file.zip';

问题是执行上面的JavaScript会尝试“卸载”当前窗口/表单,这在我这种情况下行不通。
是否有一种仅使用PHP就能“强制”下载文件(在这种情况下为'file.zip')的解决方案?

Content-Transfer-Encoding 不是一个 HTTP 头部。只是这么说一下。 - DaSourcerer
2个回答

2
$file_url = 'http://www.myremoteserver.com/file.exe';
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary"); 
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\""); 
readfile($file_url); // do the double-download-dance (dirty but worky)

此外,请确保根据文件类型添加适当的内容类型,例如应用程序/zip,应用程序/pdf等。但是,仅在您不想触发“另存为”对话框时才这样做。

1
我有两个例子,它们在编程中很有用,实际上有三个。
HTML
<a href="save_file_1.php">Click here</a>

PHP(save_file_1.php)

<?php
$file = 'example.zip';

 if(!file)
 {
     die('file not found');
 }
 else
 {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename='.basename($file));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        ob_clean();
        flush();
        readfile($file);
        exit;
 }
?>

第二个是简短而简洁的。

一个对话框会提示用户保存到...

HTML

<a href="save_file_2.php">Click here</a>

PHP(save_file_2.php)

<?php
header('Content-Disposition: attachment; filename=example.zip');
readfile("example.zip");
?>

而且这是上述示例的变体:

<?php
$file = "example.zip";
header("Content-Disposition: attachment; filename=$file");
readfile("$file");
?>

我已在使用PHP版本5.4.20的托管服务器上测试并验证了这些内容(对于我来说)可用。


谢谢,这将创建文件(就像我的示例),但仍然尝试“卸载”当前表单。这意味着,Chrome或Firefox(或任何浏览器)将显示...“您确定要离开此页面吗?”警报框。 - Gandalf
不用谢。我需要看到你的表单或HTML(所有/完整代码),包括与你现在展示的代码一起使用的任何其他PHP代码。@Gandalf 如果你还在与我的/你的代码一起使用JS,那么可能是它的问题。你现在的代码使用中有些地方引起了这个问题。 - Funk Forty Niner
附言:我也使用Firefox(最新版本),它没有生成那个消息,所以显然与您未显示的代码/HTML有关。@Gandalf - Funk Forty Niner

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接