分智科技  ›  后端开发  ›  PHP  ›  正文

PHP通过header下载文件中文名称乱码的解决办法

分智科技   622   2017-01-25

PHP 通过 header 实现文件下载,特别要注意在 IE 环境下中文乱码的问题,下面是具体的解决办法:

<?php
$ua = $_SERVER["HTTP_USER_AGENT"];

$filename = "中文文件名.txt";
$encoded_filename = urlencode($filename);
$encoded_filename = str_replace("+", "%20", $encoded_filename);

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 {
    header('Content-Disposition: attachment; filename="' . $filename . '"');
}

header('Content-Length: ' . filesize($filename));
header('Content-Type: application/octet-stream');
header('Content-Encoding: none');
header('Content-Transfer-Encoding: binary');
@readfile($filename);
?>

版权声明:本文为分智科技原创文章,未经允许不得转载。