Home >Backend Development >PHP Tutorial >PHP code to implement file download (multiple file formats)

PHP code to implement file download (multiple file formats)

WBOY
WBOYOriginal
2016-07-25 08:58:521121browse
  1. /**

  2. * File download
  3. * Multiple file formats, including pdf, zip, gif, jpg, mpeg, word, etc.
  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. ?>

复制代码


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn