Wednesday 5 December 2012

Force Download a file in PHP


PHP allows you to change the HTTP headers of files you're writing. This way you can force a file to be downloaded that normally the browser would load in the same window.  You can use this for files like PDFs, document files, images, or videos that you want your customers to download rather than read online.

<?PHP
 
// Force download in PHP 
 
$file="http://yourdomain/fileurl";  
 
header("Content-Description: File Transfer");   
 
header("Content-Type: application/octet-stream");   
 
header("Content-Disposition: attachment; filename=\"$file\""); 
 
readfile($file);
 
?>
There should be no spaces or carriage returns anywhere in the file. Blank lines will cause PHP to default to text/html and your file won't download.

Hope this helps !



No comments:

Post a Comment