【问题标题】:php files to be downloaded displayed in browser instead of downloaded要下载的php文件显示在浏览器中而不是下载
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 嗨,Marcus,我已经尝试过了,但仍然得到相同的结果。
  • 删除 ob_clean();flush();。留下readfile($file);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-18
  • 1970-01-01
  • 2014-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多