How to Download File using PHP

  1. ?php  
  2. if(isset($_GET['download_file_name'])){  
  3.       $mypath = $_SERVER['DOCUMENT_ROOT']."/download/"// change the path to fit your websites document structure  
  4.       $file_location = $mypath.$_GET['download_file_name'];  
  5.       if ($fd = fopen ($file_location"r")) {  
  6.             $fsize = filesize($file_location);  
  7.             $path_parts = pathinfo($file_location);  
  8.             $ext = strtolower($path_parts["extension"]);  
  9.             switch ($ext) {  
  10.                   case "pdf":  
  11.                   header("Content-type: application/pdf"); // add here more headers for diff. extensions  
  12.                   header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a download  
  13.                   break;  
  14.                   default;  
  15.                   header("Content-type: application/octet-stream");  
  16.                   header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");  
  17.             }  
  18.             header("Content-length: $fsize");  
  19.             header("Cache-control: private"); //use this to open files directly  
  20.             while(!feof($fd)) {  
  21.                   $buffer = fread($fd, 2048);  
  22.                   echo $buffer;  
  23.             }  
  24.       }  
  25.       fclose ($fd);  
  26.       exit;  
  27. }  
  28. ?>  
  29. <a href="download.php?download_file_name=dum.pdf">Download here</a>