让 PHP 更快的提供文件下载

 $file = "/tmp/dummy.tar.gz";

  header("Content-type: application/octet-stream");

  header('Content-Disposition: attachment; filename="' . basename($file) . '"');

  header("Content-Length: ". filesize($file));

  readfile($file);

  但是这个有一个问题, 就是如果文件是中文名的话, 有的用户可能下载后的文件名是乱码.

  于是, 我们做一下修改(参考: :


$file = "/tmp/中文名.tar.gz";

  $filename = basename($file);

  header("Content-type: application/octet-stream");

  //处理中文文件名

  $ua = $_SERVER["HTTP_USER_AGENT"];

  $encoded_filename = urlencode($filename);

  $encoded_filename = str_replace("+", "%20", $encoded_filename);

  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 . '"');

  }

  header('Content-Disposition: attachment; filename="' . $filename . '"');

  header("Content-Length: ". filesize($file));

  readfile($file);

本文出自 “享受编程” 博客,谢绝转载!

你可能感兴趣的:(文件下载,File)