Force download for PDF, JPG, GIF directly from the web browser
When a user clicks on a link to a JPG file, PDF file and other kind of files from a website, the web browser normally open the file inside it. This sometimes is annoying, for example, when the browser opens a PDF file this make the computer works slowly while the PDF loads. Another reason this is annoying is that maybe you want to store the files on your computer and use or read later.
Some webmasters try to avoid this problem and force download using .zip files, but this is not an elegant solution.
There is a better method to achieve this with the help of PHP using HEADER and READFILE commands.
Here you have an example:
The PHP code that process all is:
<?
$file = $_GET['file'];
header ("Content-type: octet/stream");
header ("Content-disposition: attachment; filename=".$file.";");
header("Content-Length: ".filesize($file));
readfile($file);
exit;
?>
And the HTML link is:
<a href="process.php?file=picture.jpg">Download JPG image</a>
As you see, the only thing you must do is upload the PHP file to your site and then call it and add the file name to the PHP URL.
Note: the JPG file must be on the same folder as the PHP file.
This trick is usefull for any kind of file: JPG, GIF, PDF, etc. and work in almost all web browsers.
If you want to download the example files, just do it HERE
Simple, but effective!
8 Comments so far
Nice tutorial! very detailed
thank you, I was looking for this
du
Great Tutorial! I will use this in the future for sure! I also like hows its straight up code and easy to understand without a page long explination like some tutorials.
Wow, that’s definetly something I will need in the near future!
I really got tired of PDF’s loading when I wanted to just download them.
I know this will help out the few [insane] people still on 56k.
thanks mante - this is a great piece of code. do you mind if i use it on a commercial site i’m developing?
Thanks
Dave
Of course you can use it!
very good, had no idea that you could do this
. thx
[…] When a user clicks on a link to a JPG file, PDF file and other kind of files from a website, the web browser normally open the file inside it. This sometimes is annoying, for example, when the browser opens a PDF file this make the computer works slowly while the PDF loads. Another reason this is annoying is that maybe you want to store the files on your computer and use or read later. (full story) […]