您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
免费发信息

php做下载文件的实现代码及文件名中乱码解决方法

2024/4/18 19:50:59发布8次查看
最近有人问我做下载文件的方法,对于php方法如下:
<?php header("content-type: application/force-download"); header("content-disposition: attachment; filename=ins.jpg"); readfile("imgs/test_zoom.jpg"); ?>
第一行代码是强制下载;
第二行代码是给下载的内容指定一个名字;
第三行代码是把下载的内容读进文件中。
如何在php下载文件名中解决乱码
通过把content-type设置为application/octet-stream,可以把动态生成的内容当作文件来下载,相信这个大家都会。那么用content-disposition设置下载的文件名,这个也有不少人知道吧。基本上,下载程序都是这么写的:
<?php $filename = "document.txt"; header('content-type: application/octet-stream'); header('content-disposition: attachment; filename=' . $filename); print "hello!"; ?>
这样用浏览器打开之后,就可以下载document.txt。
但是,如果$filename是utf-8编码的,有些浏览器就无法正常处理了。比如把上面那个程序稍稍改一下:
<?php $filename = "中文 文件名.txt"; header('content-type: application/octet-stream'); header('content-disposition: attachment; filename=' . $filename); print "hello!"; ?>
把程序保存成utf-8编码再访问,ie6下载的文件名就会乱码。 ff3下下载的文件名就只有“中文”两个字。opera 9下一切正常。
输出的header实际上是这样子:
content-disposition: attachment; filename=中文 文件名.txt其实按照rfc2231的定义,多语言编码的content-disposition应该这么定义:
content-disposition: attachment; filename*="utf8''%e4%b8%ad%e6%96%87%20%e6%96%87%e4%bb%b6%e5%90%8d.txt"
即:
filename后面的等号之前要加 *
filename的值用单引号分成三段,分别是字符集(utf8)、语言(空)和urlencode过的文件名。
最好加上双引号,否则文件名中空格后面的部分在firefox中显示不出来
注意urlencode的结果与php的urlencode函数结果不太相同,php的urlencode会把空格替换成+,而这里需要替换成%20
经过试验,发现几种主流浏览器的支持情况如下:
ie6 attachment; filename="<url编码之后的utf-8文件名>"
ff3 attachment; filename="utf-8文件名"
attachment; filename*="utf8''<url编码之后的utf-8文件名>"
o9 attachment; filename="utf-8文件名"
safari3(win) 貌似不支持?上述方法都不行
这样看来,程序必须得这样写才能支持所有主流浏览器:
<?php $ua = $_server["http_user_agent"]; $filename = "中文 文件名.txt"; $encoded_filename = urlencode($filename); $encoded_filename = str_replace("+", "%20", $encoded_filename); header('content-type: application/octet-stream'); if (preg_match("/msie/", $ua)) { header('content-disposition: attachment; filename="' . $encoded_filename . '"'); } else if (preg_match("/firefox/", $ua)) { header('content-disposition: attachment; filename*="utf8\'\'' . $filename . '"'); } else { header('content-disposition: attachment; filename="' . $filename . '"'); } print 'abc'; ?>
更多php做下载文件的实现代码及文件名中乱码解决方法。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录