PHP Download Script


PHP Download Script

With PHP, you can easily make a file accessible to download. PHP goes through a series of steps to make the downloading possible. The code below shows how PHP can find a file, make an application for it to download, name the new downloadable file, open the file, output the file data and close the data. 

To download a file,
1) Make a link to the download PHP page.
Code:
2) Add the code to the my_download.php page.
Code:
<a href="mydownload.php"><b>Download file!</b></a>

$filepath = $_SERVER['DOCUMENT_ROOT']."/downloads/my_downloadable_file.pdf";
if (file_exists($filepath)) {
//download application
   header("Content-Type: application/force-download");
   //the filename will be given below
   header("Content-Disposition:filename=\"my_downloadable_file.pdf\"");
//open file in binary mode   
$my_file = fopen($filepath, 'rb');
//output data
   fpassthru($my_file);
//close file
   fclose($my_file);
}