Posted By

acosonic on 11/05/09


Tagged

php file download force


Versions (?)

Who likes this?

8 people have marked this snippet as a favorite

Vordreller
silentbob84
BrianCoyDesign
jearley
foreverfriday
qubestream
tux-world
mintcold


PHP force file download instead opening in new tab/window


 / Published in: PHP
 

URL: http://www.acosonic.com

provide file via URL var, and script will grab it & force download. Take a look at code, and add some of your filetypes if required

  1. $file_name = $_GET['file'];
  2.  
  3. // make sure it's a file before doing anything!
  4. if(is_file($file_name))
  5. {
  6.  
  7. /*
  8.   Do any processing you'd like here:
  9.   1. Increment a counter
  10.   2. Do something with the DB
  11.   3. Check user permissions
  12.   4. Anything you want!
  13.   */
  14.  
  15. // required for IE
  16. if(ini_get('zlib.output_compression')) { ini_set('zlib.output_compression', 'Off'); }
  17.  
  18. // get the file mime type using the file extension
  19. switch(strtolower(substr(strrchr($file_name,'.'),1)))
  20. {
  21. case 'pdf': $mime = 'application/pdf'; break;
  22. case 'zip': $mime = 'application/zip'; break;
  23. case 'jpeg':
  24. case 'jpg': $mime = 'image/jpg'; break;
  25. default: $mime = 'application/force-download';
  26. }
  27. header('Pragma: public'); // required
  28. header('Expires: 0'); // no cache
  29. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  30. header('Cache-Control: private',false);
  31. header('Content-Type: '.$mime);
  32. header('Content-Disposition: attachment; filename="'.basename($file_name).'"');
  33. header('Content-Transfer-Encoding: binary');
  34. header('Content-Length: '.filesize($file_name)); // provide file size
  35. readfile($file_name); // push it out
  36. exit();
  37.  
  38. }

Report this snippet  

You need to login to post a comment.