PHP File Download Function


Generally if we put direct links to images , .txt , .pdf in web pages they will open in browser . Sometimes we need to prompt the user with a dialog box to download and save the file ..
here is an example of such function which will download the file rather than  opening it






code :

function FileDownload($file,$DownloadName="")
{ 
  
  $DLFileName=($DownloadName==""? $file : $DownloadName);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($DLFileName));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
if(file_exists($file))
readfile($file);
exit;


}

$file is the name of the original file with the location.
$DownloadName is an optional argument which can be used to save the file with other name rather than with the name it is kept on server.

eg: FileDownload('images/uid567980.jpg','jerry.jpg')
 this will download a file uid567980.jpg from  images folder and prompt the user to download and save with a name 'jerry.jpg'


How to Use this function 


Suppose we need to download a PDF file .
We put the download link on a page like this
<a href='downloadfile.php?file=myprofile.pdf'>Click to Downlod</a>

and in downloadfile.php we use

$file=$_GET['file'];
FileDownload($file);

For extra security we can use a database to save the file location
For each file, a unique fileid (primary key)and filelocation is kept in Database table.
Pass the fileid rather than filename as arguments in the url 
In downloadfile.php we will fetch the corresponding file from the fileid using the database table
Pass the filename to function and it wil prompt the file download box.
This method is followed by major file sharing sites.