简体   繁体   English

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

[英]php files to be downloaded displayed in browser instead of downloaded

I am trying to get a text file to download using a PHP script but when my script runs the file contents are displayed in the browser window. 我试图使用PHP脚本下载文本文件,但是当脚本运行时,文件内容显示在浏览器窗口中。 I tried this solution: Why downloaded file is not downloaded instead it is shown in browser? 我尝试了以下解决方案: 为什么不下载下载的文件,而是显示在浏览器中? However the code I have already has a content length header. 但是我已经有的代码具有内容长度标头。 This is my PHP code (which I obtained from another post 1 and modified for a text file) 这是我的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 浏览器输出的文本文件内容

I tried to copy an example from php.com for a pdf file and I get the same symbols as in the post I linked. 我试图从php.com复制一个示例以获取pdf文件,但得到的符号与我链接的帖子中的符号相同。

I am not sure why this is happening. 我不确定为什么会这样。 I am running MAMP 3.5 with PHP version 5.6.10 on Chrome. 我在Chrome上使用PHP版本5.6.10运行MAMP 3.5。

This has really baffled me since so far I have been able to find solutions online for everything I have done. 自从到目前为止,我已经能够在线找到我所做的所有解决方案,这真让我感到困惑。 As far as I can tell, what I am doing is correct so any advice would be much appreciated. 据我所知,我在做什么是正确的,因此任何建议都将不胜感激。

Many thanks, 非常感谢,

Nehal Patel 尼尔·帕特尔(Nehal Patel)

RESOLVED (9/4/15) with guidance from Marcus: removed flush() an ob_clean(). 在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;

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM