【问题标题】:PHP file download strange errorPHP文件下载奇怪的错误
【发布时间】:2014-09-09 14:34:35
【问题描述】:

通过 PHP 下载文件时出现错误。

代码:

if(file_exists($myFile)) {
  $mm_type="application/octet-stream";

  header("Cache-Control: public, must-revalidate");
  header("Pragma: hack"); // WTF? oh well, it works...
  header("Content-Type: " . $mm_type);
  header("Content-Length: " .(string)(filesize($myFile)) );
  header('Content-Disposition: attachment; filename="'.basename($filename).'"');
  header("Content-Transfer-Encoding: binary\n");

  $fp = fopen($myFile, 'rb');
  $buffer = fread($fp, filesize($myFile));
  fclose ($fp);

  print $buffer;
}

以上代码适用于 doc 文件、pdf 文件、zip 文件、jpg/png 文件,

但当我尝试下载 .rtf 或 .txt 文件时失败。

在所有主流浏览器(Chrome、FF、IE、Safari)上测试。

还尝试使用 as mime-type : application/force-download 没有运气。

错误:

我在 Chrome 中遇到错误:

This webpage is not available

在 Firefox 中:

The page isn't redirecting properly

Firefox has detected that the server is redirecting the request for this address in a way that will never complete.

【问题讨论】:

  • 对你来说“不工作”是什么意思?
  • 旁注,也可以使用filename="'.basename($filename).'"
  • 进行了编辑,描述了我遇到的错误
  • @LozCheroneツ 感谢您的来信
  • 您的错误不在您的下载脚本中。循环重定向是由其他原因引起的。检查你有重定向的代码。

标签: php file download rtf


【解决方案1】:

您需要为 .rtf 和 .txt 文件添加内容类型

先检查文件扩展名,然后在

if else 条件您为 .rtf 和 .txt 文件设置内容类型

干杯:)

我认为这应该可以帮助您在这里找到所有内容类型

http://www.sitepoint.com/web-foundations/mime-types-complete-list/

【讨论】:

    【解决方案2】:

    这段代码解决了问题:

    if (file_exists($myFile)) {
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename='.basename($filename));
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($myFile));
            readfile($myFile);
            exit;
        }
    

    来源:PHP.net

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-12
      • 2011-05-17
      • 1970-01-01
      • 2013-12-23
      相关资源
      最近更新 更多