php mandatory download of the file code (IE under the Chinese filename to solve the problem)

  • 2020-05-05 11:01:22
  • OfStack

One of the problems encountered in the middle is that the submitted Chinese file name is directly put into header, which will become messy under IE. The solution is to put the file name into header after urlencode, 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 PHP Header file in IE. One is to change the page code to utf8, and the other is to enter urlencode code for url.
Solution 1 (my page is utf-8) :

 
$filename = " Chinese .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 2:

Put the file name urlencode first and then header, as shown below.
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']); 
?> 

Related articles: