PHP附件下载中文名称乱码的解决方法

php一段代码,处理文件下载时的文件名,后来客户反馈说firefox,safari下的中文文件名不能正常显示。

        $file_info['title'] = rawurlencode($file_info['title']);
        $filename=iconv('utf-8', 'gbk', $file_info['title']);
        header("Content-Disposition:attachment;filename = " . $filename);

修正为以下内容后firefox,safari下正常显示

如果没有兴趣请看简版,一句话解决
if (preg_match("/Safari/", $ua)) { 
header( 'Content-Disposition: attachment; filename*="UTF-8\'\'' .  rawurlencode($file_info['title']) );
}

之前试过和firefox一样处理方法,结果下载的文件名连扩展名都没有了
 header( 'Content-Disposition: attachment; filename*=UTF-8\'\'' .  rawurlencode($file_info['title'])  . '"' ); 

兜兜转转后发现去掉一对双引号就可以,

求此时此刻内心的阴影面积

一堆代码参考一下。


       $filename = "中文 文件名.txt";
$encoded_filename = urlencode($filename);
$encoded_filename = str_replace("+", "%20", $encoded_filename);
//        header("Content-Disposition:attachment;filename = " . $filename);


        $encoded_filename =  $file_info['title'] 
        $ua = $_SERVER["HTTP_USER_AGENT"];
        //IE
        if(preg_match("/MSIE/", $ua) || preg_match("/Trident\/7.0/", $ua)){
            header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
        } else if (preg_match("/Firefox/", $ua)) {
            header('Content-Disposition: attachment; filename*="utf8\'\'' . $filename . '"');
        } else if (preg_match("/Safari/", $ua)) {
            header( 'Content-Disposition: attachment; filename*=UTF-8\'\'' . $encoded_filename );
        } else {
            header('Content-Disposition: attachment; filename="' . $filename . '"');
        }
posted @ 2020-09-26 17:43  Vitascope  阅读(240)  评论(1编辑  收藏  举报