【问题标题】:PHP readfile() causing pdf to render in browser, not downloadingPHP readfile()导致pdf在浏览器中呈现,而不是下载
【发布时间】:2014-12-12 15:42:30
【问题描述】:

我正在尝试强制下载文件,但我得到的只是浏览器窗口中的一串随机未知字符。包含代码:

$file_url = "docs/$c/$path";
header('Content-Description: File Transfer');
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=$title.$type");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers 
header("Content-Transfer-Encoding: binary");
header("Pragma: public");
header("Content-Length: ".filesize($file_url));
readfile($file_url);

这已经持续了大约一个星期,我快疯了。任何帮助表示赞赏。 谢谢。

【问题讨论】:

    标签: php header download readfile


    【解决方案1】:

    我怀疑您的 Content-Disposition 标头是问题所在。

    试试这个版本:

    header("Content-Disposition: attachment; filename=\"$title.$type\"");
    

    【讨论】:

      【解决方案2】:

      我遇到了同样的错误。使用 ob_clean() 和 flush() 帮助了我的情况。我使用了下面的代码:

      header('Content-Description: File Transfer');
      header('Content-Type: application/octet-stream');
      header('Content-disposition: attachment; filename='.$filename.'.pdf');
      header('Expires: 0');
      header('Cache-Control: must-revalidate');
      header('Pragma: public');
      header('Content-type: application/force-download');
      header( 'Content-transfer-encoding: binary' ); 
      ob_clean();
      flush();
      readfile('Reports/'.$filename.'.pdf');
      exit;
      

      【讨论】:

      • 它帮助我解决了另一个问题:收到的文件中有一个额外的字节。现在好了。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-18
      • 1970-01-01
      • 2019-05-07
      相关资源
      最近更新 更多