PHP下载文件名中文乱码解决方法,如果文件名是中文的或者有空格,下载时会出现乱码,很是麻烦。解决方法如下:
兼容“Safari、ie6-11、ie-edge、chrome、Firefox”等各大主流浏览器
$buffer = 102400;
$ua = $_SERVER["HTTP_USER_AGENT"];
$name = "";
$file = "/upload/images/avatar/头像 001.jpg";
// 文件名处理
if(empty($name)) $name = time();
$ext = explode('?',pathinfo($file,PATHINFO_EXTENSION));
if(empty(pathinfo($name,PATHINFO_EXTENSION))){
$name = $name.'.'.$ext[0];
}
$encoded_filename = urlencode($name);
$encoded_filename = str_replace("+", "%20", $encoded_filename);
// 网络文件
if(stripos($file,'http://',0)===0 || stripos($file,'https://',0) === 0){
$file = @ fopen($file, "r");
if (!$file) {
echo "文件找不到。";
} else {
header("Content-type: application/octet-stream");
// 浏览器判断
if(preg_match("/MSIE/", $ua) || preg_match("/Trident\/7.0/", $ua) || preg_match("/Edge/", $ua)){
header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
} else if (preg_match("/Firefox/", $ua)) {
header('Content-Disposition: attachment; filename*="utf8\'\'' . $name . '"');
} else {
header('Content-Disposition: attachment; filename="' . $name . '"');
}
while (!feof($file)) {
echo fread($file, $buffer);
}
fclose($file);
}
}
// 本地文件
else{
if (!file_exists($file)) echo "文件找不到。";
$fp = fopen($file, "r");
$fileSize = filesize($file);
$fileData = '';
while (!feof($fp)) {
$fileData .= fread($fp, $buffer);
}
fclose($fp);
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type:application/octet-stream;");
header("Accept-Ranges:bytes");
header("Accept-Length:{$fileSize}");
// 浏览器判断
if(preg_match("/MSIE/", $ua) || preg_match("/Trident\/7.0/", $ua) || preg_match("/Edge/", $ua)){
header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
} else if (preg_match("/Firefox/", $ua)) {
header('Content-Disposition: attachment; filename*="utf8\'\'' . $name . '"');
} else {
header('Content-Disposition: attachment; filename="' . $name . '"');
}
header("Content-Transfer-Encoding: binary");
echo $fileData;
}