强制PHP下载文件时,显示未知符号
问题描述:
我有一个问题,迫使PHP下载一个文件,当我运行这段代码:强制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
----------------------------------------------------------
答
在响应头您刚刚发布没有Content-Disposition: attachment
出现.. 。你应该放弃呼叫ob_clean()
(或者,至少在header()
*之前移动它)。
此外,该flush()
是完全没有意义(什么是冲洗一个空的缓冲区?)。去掉它。
*只要你叫ob_start()
事先 - 通常是在你的脚本开始
你的代码看起来不够理智。 '$ mimetype'的价值是什么,因为这是告诉浏览器你给的是什么类型的文件。你是否收到任何错误或警告? – IMSoP
你可以发布你正在发送的标题吗?否则,将很难给出有意义的答案... – CAFxX
**请**发布您正在发送的标题。 – CAFxX