当前位置:Gxlcms > PHP教程 > php文件下载(防止中文文件名乱码)的示例代码

php文件下载(防止中文文件名乱码)的示例代码

时间:2021-07-01 10:21:17 帮助过:14人阅读

  1. /**
  2. * php文件下载代码,中文无乱码
  3. * by bbs.it-home.org
  4. */
  5. $file = "/tmp/中文名.tar.gz";
  6. $filename = basename($file);
  7. header("Content-type: application/octet-stream");
  8. //处理中文文件名
  9. $ua = $_SERVER["HTTP_USER_AGENT"];
  10. $encoded_filename = urlencode($filename);
  11. $encoded_filename = str_replace("+", "%20", $encoded_filename);
  12. if (preg_match("/MSIE/", $ua)) {
  13. header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
  14. } else if (preg_match("/Firefox/", $ua)) {
  15. header("Content-Disposition: attachment; filename*=\"utf8''" . $filename . '"');
  16. } else {
  17. header('Content-Disposition: attachment; filename="' . $filename . '"');
  18. }
  19. header('Content-Disposition: attachment; filename="' . $filename . '"');
  20. header("Content-Length: ". filesize($file));
  21. readfile($file);

另外,有兴趣的朋友,可以研究下apache服务器中的module mod_xsendfile模块,可以用它来提高PHP发送文件的效率。

人气教程排行