Thursday, January 15, 2009

Force download dialogue box using PHP

Here is a PHP script for Opening a download dialogue box when clicks on a Download link. Save the below script as 'download.php' & Point your download link to 'download.php' & also Pass the name of the file to be downloaded to 'download.php'
For eg:
If file to be downloaded is jenson.mp3, then put a Download link as <a href="download.php?file=<?=$filename?>">Download</a> [$filename is the variable for 'jenson.mp3'] on any page. That'll work for you.


// downloading a file--JensON-- 
$filename "jenson/upload/".$_GET['file'];//$_GET is used for getting the filename 
//[jenson/upload/ is the directory where jenson.mp3 file stored] 
// fix for IE catching or PHP bug issue 
header("Pragma: public"); 
header("Expires: 0"); // set expiration time 
header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
// browser must download file from server instead of cache 

// force download dialog 
header("Content-Type: application/force-download"); 
header("Content-Type: application/octet-stream"); 
header("Content-Type: application/download"); 

// use the Content-Disposition header to supply a recommended filename and 
// force the browser to display the save dialog. 
header("Content-Disposition: attachment; filename=".basename($filename).";"); 

/* 
The Content-transfer-encoding header should be binary, since the file will be read 
directly from the disk and the raw bytes passed to the downloading computer. 
The Content-length header is useful to set for downloads. The browser will be able to 
show a progress meter as a file downloads. The content-lenght can be determines by 
filesize function returns the size of a file. 
*/ 
header("Content-Transfer-Encoding: binary"); 
header("Content-Length: ".filesize($filename)); 

@
readfile($filename); 
exit(
0); 
?>


Juz copy & paste the above php script as 'download.php'. Follow the steps mentioned above. Happy coding, Enjoy!

No comments:

Post a Comment