Posted By

welancers on 08/17/12


Tagged

php download force


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

tux-world
IMPGTX


Force file download using PHP


 / Published in: PHP
 

Simply pass the file name with path as an argument to this function and it will force that file downloading.

  1. function download_file($file){
  2. $file = $file; //Set File Location
  3. if (file_exists($file)) { // Check if file exists
  4. if(!is_dir($file)){ // Check if it is a directory or a file
  5. // The following files will set the headers to the file download
  6. header('Content-Description: File Transfer');
  7. header('Content-Type: application/octet-stream');
  8. header('Content-Disposition: attachment; filename='.basename($file));
  9. header('Content-Transfer-Encoding: binary');
  10. header('Expires: 0');
  11. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  12. header('Pragma: public');
  13. header('Content-Length: ' . filesize($file));
  14. ob_clean(); // Clear any set cookies/headers.
  15. flush(); // Flush
  16. readfile($file); // Actually Start The Download
  17. return "Downloading $file"; // Return Downloading FILE_NAME
  18. exit; // Stop Processing
  19. }else{ // If file is a directory
  20. return "You have selected to download a directory. Download Cancelled"; // Show error
  21. }
  22. }else{ // If file doesnt exist
  23. return "File doesnt exist";
  24. }
  25. }

Report this snippet  

You need to login to post a comment.