Advertisement
nbruley

force download of documents and audio

Apr 11th, 2012
1,501
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.12 KB | None | 0 0
  1. <?php
  2.  
  3. $filename = $_GET['file'];
  4.  
  5. // NOTE: YOU SHOULD HARDCODE IN A FILE LOCATION OR RESTRICT DIRECTORIES SO THAT THE ACCESS IS RESTRICTED
  6. //FOR EXAMPLE
  7. //if(substr($filename, 0,5)!='mydir') { exit; } //restrict download access to a link beginning with mydir only
  8. //the link would then be something like http://mysite.com/force-download.php?file=mydir/myFile.jpg
  9.  
  10. //http://elouai.com/force-download.php
  11. //EXAMPLE LINK http://mysite.com/force-download.php?file=bookmarks/apple-heart.jpg
  12. // required for IE, otherwise Content-disposition is ignored
  13. if(ini_get('zlib.output_compression'))
  14.   ini_set('zlib.output_compression', 'Off');
  15.  
  16. // addition by Jorg Weske
  17. $file_extension = strtolower(substr(strrchr($filename,"."),1));
  18.  
  19. if( $filename == "" )
  20. {
  21.   echo "<html><body OnLoad=\"javascript: alert('Sorry, file not found...');history.back();\" bgcolor=\"#F0F0F0\"></body></html>";
  22.   exit;
  23. } elseif ( ! file_exists( $filename ) )
  24. {
  25.   echo "<html><body OnLoad=\"javascript: alert('Sorry, file not found...');history.back();\" bgcolor=\"#F0F0F0\"></body></html>";
  26.   exit;
  27. };
  28. switch( $file_extension )
  29. {
  30.   case "pdf": $ctype="application/pdf"; break;
  31.   case "exe": $ctype="application/octet-stream"; break;
  32.   case "zip": $ctype="application/zip"; break;
  33.   case "doc": $ctype="application/msword"; break;
  34.   case "xls": $ctype="application/vnd.ms-excel"; break;
  35.   case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
  36.   case "gif": $ctype="image/gif"; break;
  37.   case "png": $ctype="image/png"; break;
  38.   case "jpeg":
  39.   case "jpg": $ctype="image/jpg"; break;
  40.   default: $ctype="application/force-download";
  41. }
  42. header("Pragma: public"); // required
  43. header("Expires: 0");
  44. header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  45. header("Cache-Control: private",false); // required for certain browsers
  46. header("Content-Type: $ctype");
  47. // change, added quotes to allow spaces in filenames, by Rajkumar Singh
  48. header("Content-Disposition: attachment; filename=\"".basename($filename)."\";" );
  49. header("Content-Transfer-Encoding: binary");
  50. header("Content-Length: ".filesize($filename));
  51. readfile("$filename");
  52. exit();
  53.  
  54. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement