要下载的php文件显示在浏览器中,而不是下载的


php files to be downloaded displayed in browser instead of downloaded

我正试图使用PHP脚本下载一个文本文件,但当我的脚本运行时,文件内容会显示在浏览器窗口中。我尝试了这个解决方案:为什么下载的文件没有下载,而是显示在浏览器中?然而,我已经有了一个内容长度的标题。这是我的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;

文本文件内容的浏览器输出

我试图从php.com上复制一个pdf文件的例子,我得到了与我链接的帖子中相同的符号。

我不知道为什么会发生这种事。我在Chrome上运行的是MAMP 3.5,PHP版本为5.6.0。

这真的让我很困惑,因为到目前为止,我已经能够在网上找到我所做的一切的解决方案。据我所知,我所做的是正确的,所以任何建议都将不胜感激。

非常感谢,

Nehal Patel

在Marcus的指导下解决(2015年9月4日):删除了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;

尝试将内容类型更改为八位字节/流

header('Content-Type: application/octet-stream');