| Subcribe via RSS

Download Code

October 9th, 2007 Posted in PHP

This code is something i found that will force download, rather than opening in browser:

PHP:
  1. <?php
  2. $filename = $my_file_name;
  3. if(substr($filename,0,1) != "/"){
  4.     $filename = "/". $filename;
  5. }
  6.  
  7. if(ini_get('zlib.output_compression'))
  8.   ini_set('zlib.output_compression', 'Off');
  9.  
  10. $file_extension = strtolower(substr(strrchr($filename,"."),1));
  11.  
  12. if( $filename == "" ) {
  13.     header("Location: /error.php?nofile");
  14. } elseif ( !file_exists( $filename ) ){
  15.     header("Location: /error.php?file404");
  16. };
  17. switch( $file_extension ) {
  18.     case "pdf": $ctype="application/pdf"; break;
  19.     //case "exe": $ctype="application/octet-stream"; break;
  20.     case "zip": $ctype="application/zip"; break;
  21.     case "doc": $ctype="application/msword"; break;
  22.     case "xls": $ctype="application/vnd.ms-excel"; break;
  23.     case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
  24.     case "gif": $ctype="image/gif"; break;
  25.     case "png": $ctype="image/png"; break;
  26.     case "js" : $ctype="application/x-javascript"; break;
  27.     case "jpeg":
  28.     case "jpg": $ctype="image/jpg"; break;
  29.     default: $ctype="application/force-download";
  30. }
  31. header("Pragma: public");
  32. header("Expires: 0");
  33. header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  34. header("Cache-Control: private",false);
  35. header("Content-Type: $ctype");
  36. header("Content-Disposition: attachment; filename=\"".basename($filename)."\";" );
  37. header("Content-Transfer-Encoding: binary");
  38. header("Content-Length: ".filesize($filename));
  39. readfile("$filename");
  40. exit();
  41. ?>

Leave a Reply

Preview: