PHP force file download instead opening in new tab/window


/ Published in: PHP
Save to your folder(s)

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


Copy this code and paste it in your HTML
  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. }

URL: http://www.acosonic.com

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.