PHP文件下载奇怪的错误

时间:2014-07-18 12:39:37

标签: php file download rtf

我通过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)上进行测试。

还尝试使用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.

2 个答案:

答案 0 :(得分:1)

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

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

if else条件是否设置了.rtf和.txt文件的内容类型

干杯:)

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

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

答案 1 :(得分:0)

此代码解决了问题:

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