您的位置:首页 > 编程语言 > PHP开发

【整理】解决php输出文件下载时文件名含中文时出现乱码

2011-09-28 20:11 726 查看
由于某度众所周知的举动,让我搬离写了5年的渣度空间,准备把技术性的文章定在CSDN了。这些都是文章备份。勿怪。。

相关: http://blog.csdn.net/yangsp1/article/details/4301685 (不知道是否原创)

php下载时,用一个header可以确定保存为的名字:

header( 'Content-Disposition: attachment; filename="'.$saved_name.'"' );//$saved_name存为的名字

但是如果是中文的话,在ie下是乱码。其他浏览器是正常的。

这时候,需要urlencode($saved_name),ie下可以保存为正常的中文名字了。

但是其他浏览器在url编码时候不会自动解码。

这时候就要靠判断浏览器类型了了:

===============================

if(strpos($_SERVER['HTTP_USER_AGENT'],"MSIE"))
header( 'Content-Disposition: attachment; filename="'.urlencode($this->saved_name).'"' );//如果是ie存为的名字要urlencode
else

header( 'Content-Disposition: attachment; filename="'.$this->saved_name.'"' );//存为的名字

=====================

即可解决。

另:输出文件的header写法:

========================================

header( "Pragma: public" );
header( "Expires: 0" ); // 一定要设置不缓存哦。
header( "Cache-Component: must-revalidate, post-check=0, pre-check=0" );
header( "Content-type:".$mineType );
header( "Content-Length: " . filesize( $path) );
if(strpos($_SERVER['HTTP_USER_AGENT'],"MSIE"))
header( 'Content-Disposition: attachment; filename="'.urlencode($saved_name).'"' );//如果是ie存为的名字要urlencode
else header( 'Content-Disposition: attachment; filename="'.$saved_name.'"' );//存为的名字
header( 'Content-Transfer-Encoding: binary' );
readfile( $path);//读取并输出


======================

PS:在csdn上下载文件,非ie浏览器下载时候,就会莫名其妙的文件名成了一堆url编码,原来csdn也没判断浏览器,只照顾ie输出中文名么?还有右边那堆排名列表在opera下的错位让人都懒得吐槽了。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息