【发布时间】:2016-04-09 14:34:06
【问题描述】:
我正在尝试使用 PHP 脚本获取要下载的文本文件,但是当我的脚本运行时,文件内容会显示在浏览器窗口中。我试过这个解决方案:Why downloaded file is not downloaded instead it is shown in browser? 但是,我已经有一个内容长度标头的代码。这是我的 PHP 代码(我从另一个帖子 1 获得并修改为文本文件)
$file = 'file.txt';
header('Content-Description: File Transfer');
header('Content-Type: text/plain');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
Browser output of text file contents
我试图从 php.com 复制一个 pdf 文件的示例,我得到的符号与我链接的帖子中的相同。
我不确定为什么会这样。我在 Chrome 上运行 MAMP 3.5 和 PHP 版本 5.6.10。
这真的让我很困惑,因为到目前为止,我已经能够在网上找到我所做的一切的解决方案。据我所知,我所做的是正确的,所以任何建议都会非常感激。
非常感谢,
尼哈尔·帕特尔
在 Marcus 的指导下解决了 (9/4/15): 删除了 flush() 和 ob_clean()。
$file = 'file.txt';
header('Content-Description: File Transfer');
header('Content-Type: text/plain');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
【问题讨论】:
-
我曾经将
'Content-Disposition: attachment更改为'Content-Disposition: inline并显示在新选项卡中,但这不再起作用。不确定。
标签: php