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

时间:2013-12-22 01:44:20

标签: javascript php

我希望用户在他/她点击“下载此文件”链接时下载文件。

用例:用户点击链接,网络应用会生成一个文件并将其“推送”下载。

我有以下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')下载?

2 个答案:

答案 0 :(得分: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,application / pdf等添加适当的内容类型 - 但仅限于您不想触发另存为对话框。

答案 1 :(得分: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在托管服务器上测试和工作(对我来说)。

相关问题