Home > Article > Backend Development > Win7 displays the file suffix name. Code to force file download in PHP (solve the problem of garbled Chinese file names under IE)
A problem encountered in the middle is that the Chinese file name submitted directly into the header will become garbled under IE. The solution is to urlencode the file name first and then put it into the header, as follows.
The code is as follows:
<?php $file_name = urlencode($_REQUEST['filename']); header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Content-Type: application/force-download"); header('Content-Type: application/vnd.ms-excel; charset=utf-8'); header("Content-Transfer-Encoding: binary"); header('Content-Disposition: attachment; filename='.$file_name); echo stripslashes($_REQUEST['content']); ?>
There are two common ways to solve the problem of Chinese garbled characters in the IE file name of PHP Header downloaded files. One is to change the page encoding to utf8, and the other is to enter urlencode encoding for the Chinese URL. .
Solution one (my page is utf-8 encoded):
The code is as follows:
$filename = "中文.txt"; $ua = $_SERVER["HTTP_USER_AGENT"]; $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 . '"'); }
Solution two
Urlencode the file name first and then put it into the header, as follows.
The code is as follows:
The code is as follows:
<?php $file_name = urlencode($_REQUEST['filename']); header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Content-Type: application/force-download"); header('Content-Type: application/vnd.ms-excel; charset=utf-8'); header("Content-Transfer-Encoding: binary"); header('Content-Disposition: attachment; filename='.$file_name); echo stripslashes($_REQUEST['content']); ?>
The above is the code for forced downloading of files in win7 display file suffix name in php (solve the problem of garbled Chinese file names under IE). For more related content, please pay attention to the PHP Chinese website (www.php.cn)!