-1

当我运行此代码时,我在强制 php 下载文件时遇到问题:

  $file = "storage/".$filename;
  header('Content-Description: File Transfer');
  header('Content-Type: '.$mimetype);
  header('Content-Disposition: attachment; filename='.basename($originalfilename));
  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();

它不会强制浏览器下载文件,而是显示文件的所有内容。例如,当我想强制浏览器下载 test.png 时,浏览器本身会显示很多未知符号(exp. �q�M�6�%V�һK..)。如何强制浏览器下载文件而不是显示它?

我使用了实时 HTTP 标头,当我单击此页面中的下载按钮时: http ://www.helios.ir/get.php?file=17/dl.php?name=56379948c6df5e49d3073aee14358e3fc98ba5ae.jpg

它显示了这个标题:

----------------------------------------------------------
http://www.helios.ir/download.php?file=17.jpg&name=56379948c6df5e49d3073aee14358e3fc98ba5ae.jpg

GET /download.php?file=17.jpg&name=56379948c6df5e49d3073aee14358e3fc98ba5ae.jpg HTTP/1.1
Host: www.helios.ir
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:14.0) Gecko/20100101 Firefox/14.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
DNT: 1
Connection: keep-alive
Referer: http://www.helios.ir/get.php?file=17/dl.php?name=56379948c6df5e49d3073aee14358e3fc98ba5ae.jpg
Cookie: mfh_mylang=en; mfh_sess_id=effccfb2429a54b6f26ef2f155144c98; mfh_logined=0; mfh_uid=0; mfh_last_click=1345470635; __utma=44342077.1613075140.1345761327.1345912829.1345927090.14; __utmz=44342077.1345910409.12.11.utmcsr=localhost|utmccn=(referral)|utmcmd=referral|utmcct=/share6/get.php; __utmb=44342077.18.10.1345927090; PHPSESSID=bb18789f8011836092f4e2d14aa3118d; __utmc=44342077

HTTP/1.1 200 OK
Date: Sat, 25 Aug 2012 22:25:01 GMT
Server: Apache/2.2.22 (CentOS)
X-Powered-By: PHP/5.2.17
Connection: close
Transfer-Encoding: chunked
Content-Type: text/html; charset=UTF-8
----------------------------------------------------------
4

1 回答 1

1

在您刚刚发布的响应标头中没有Content-Disposition: attachment出现...您可能应该挂断ob_clean()电话(或者,至少,将其移到header()电话之前*)。

此外,这flush()完全没有意义(刷新空缓冲区有什么意义?)。去掉它。


*前提是你事先打电话ob_start()- 通常在你的脚本开始

于 2012-08-25T22:34:04.517 回答