首頁 > 後端開發 > php教程 > php實作檔案下載(多種檔案格式)的程式碼

php實作檔案下載(多種檔案格式)的程式碼

WBOY
發布: 2016-07-25 08:58:52
原創
1118 人瀏覽過
  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. ?>

复制代码


來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板