当前位置:Gxlcms > PHP教程 > php下载文件的函数示例(图文)

php下载文件的函数示例(图文)

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

分享一个php下载函数,用于下载指定的文件,不限文件格式。有需要的朋友参考下。

php下载文件的函数举例,如下:

  1. <!--?php
  2. /**
  3. * php下载文件
  4. * $filename=$_SERVER['DOCUMENT_ROOT']."/test/file/20130503/20130503150036_85945.doc";
  5. * $title="下载测试9";
  6. * down($filename,$title);
  7. * edit by bbs.it-home.org
  8. */
  9. //$filename 必须是路径,不是url
  10. function down($filename,$title=''){
  11. $file = fopen($filename,"r");
  12. $filesize = filesize($filename);
  13. $encoded_filename = urlencode($title);
  14. $encoded_filename = str_replace("+", "%20", $title);
  15. $ua = $_SERVER["HTTP_USER_AGENT"];
  16. if (preg_match("/MSIE/is", $ua)) {
  17. $file_name = urlencode($title);
  18. header("Pragma: public"); header("Expires: 0");
  19. header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  20. header("Content-Type: application/force-download");
  21. header('Content-Type: application/vnd.ms-excel; charset=utf-8');
  22. header("Content-Transfer-Encoding: binary");
  23. header('Content-Disposition: attachment; filename='.$file_name);
  24. } else {
  25. header('Content-Type: application/octet-stream');
  26. if (preg_match("/Firefox/is", $ua)) {
  27. header('Content-Disposition: attachment; filename*="utf8\'\'' . $title . '"');
  28. } else {
  29. header('Content-Disposition: attachment; filename="' . $title . '"');
  30. }
  31. }
  32. echo fread($file, $filesize);
  33. fclose($file);
  34. }
  35. ?-->

运行效果如下图: php下载文件的函数

人气教程排行