欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php实现文件下载(多种文件格式)的代码

程序员文章站 2022-03-07 16:11:12
...
  1. /**

  2. * 文件下载
  3. * 多种文件格式,包括pdf、zip、gif、jpg、mpeg、word等。
  4. * edit bbs.it-home.org
  5. */
  6. function dl_file($file){
  7. //First, see if the file exists
  8. if (!is_file($file)) { die("404 File not found!"); }
  9. //Gather relevent info about file

  10. $len = filesize($file);
  11. $filename = basename($file);
  12. $file_extension = strtolower(substr(strrchr($filename,"."),1));
  13. //This will set the Content-Type to the appropriate setting for the file

  14. switch( $file_extension ) {
  15. case "pdf": $ctype="application/pdf"; break;
  16. case "exe": $ctype="application/octet-stream"; break;
  17. case "zip": $ctype="application/zip"; break;
  18. case "doc": $ctype="application/msword"; break;
  19. case "xls": $ctype="application/vnd.ms-excel"; break;
  20. case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
  21. case "gif": $ctype="image/gif"; break;
  22. case "png": $ctype="image/png"; break;
  23. case "jpeg":
  24. case "jpg": $ctype="image/jpg"; break;
  25. case "mp3": $ctype="audio/mpeg"; break;
  26. case "wav": $ctype="audio/x-wav"; break;
  27. case "mpeg":
  28. case "mpg":
  29. case "mpe": $ctype="video/mpeg"; break;
  30. case "mov": $ctype="video/quicktime"; break;
  31. case "avi": $ctype="video/x-msvideo"; break;
  32. //The following are for extensions that shouldn't be downloaded (sensitive stuff, like php files)

  33. case "php":
  34. case "htm":
  35. case "html":
  36. case "txt": die("Cannot be used for ". $file_extension ." files!"); break;
  37. default: $ctype="application/force-download";

  38. }
  39. //Begin writing headers

  40. header("Pragma: public");
  41. header("Expires: 0");
  42. header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  43. header("Cache-Control: public");
  44. header("Content-Description: File Transfer");
  45. //Use the switch-generated Content-Type
  46. header("Content-Type: $ctype");
  47. //Force the download

  48. $header="Content-Disposition: attachment; filename=".$filename.";";
  49. header($header );
  50. header("Content-Transfer-Encoding: binary");
  51. header("Content-Length: ".$len);
  52. @readfile($file);
  53. exit;
  54. }
  55. ?>
复制代码