Home  >  Article  >  Backend Development  >  PHP code to force download files (solve the problem of garbled Chinese file names under IE)

PHP code to force download files (solve the problem of garbled Chinese file names under IE)

WBOY
WBOYOriginal
2016-07-25 08:54:47673browse
  1. $file_name = urlencode($_REQUEST['filename']);
  2. header("Pragma: public"); header("Expires: 0");
  3. header("Cache-Control : must-revalidate, post-check=0, pre-check=0");
  4. header("Content-Type: application/force-download");
  5. header('Content-Type: application/vnd.ms-excel ; charset=utf-8');
  6. header("Content-Transfer-Encoding: binary");
  7. header('Content-Disposition: attachment; filename='.$file_name);
  8. echo stripslashes($_REQUEST['content ']);
  9. ?>
Copy the code

to solve the problem of garbled Chinese characters in the IE file name of PHP Header downloaded files: One is to change the page encoding to utf8. The other is to enter urlencode encoding for Chinese URLs.

Let’s look at the specific implementation code of the solution. 1. The page is utf-8 encoded:

  1. $filename = "中文.txt";
  2. $ua = $_SERVER["HTTP_USER_AGENT"];
  3. $encoded_filename = urlencode($filename);
  4. $encoded_filename = str_replace("+ ", "%20", $encoded_filename);
  5. header('Content-Type: application/octet-stream');
  6. if (preg_match("/MSIE/", $ua)) {
  7. header('Content-Disposition : attachment; filename="' . $encoded_filename . '"');
  8. } else if (preg_match("/Firefox/", $ua)) {
  9. header('Content-Disposition: attachment; filename*="utf8' '' . $filename . ''');
  10. } else {
  11. header('Content-Disposition: attachment; filename="' . $filename . ''');
  12. }
Copy code

2, Urlencode the file name first and then put it into the header. Code:

  1. $file_name = urlencode($_REQUEST['filename']);
  2. header("Pragma: public"); header("Expires: 0");
  3. header("Cache- Control: must-revalidate, post-check=0, pre-check=0");
  4. header("Content-Type: application/force-download"); //Add forced download header information
  5. header('Content- Type: application/vnd.ms-excel; charset=utf-8');
  6. header("Content-Transfer-Encoding: binary");
  7. header('Content-Disposition: attachment; filename='.$file_name);
  8. echo stripslashes($_REQUEST['content']);
  9. ?>
Copy code


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn