Some tricks

Tricks for web designers and developers

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:

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

  1. Pepper May 6th, 2006 6:18 pm

    Nice tutorial! very detailed

  2. Adu May 6th, 2006 9:19 pm

    thank you, I was looking for this :)

    du

  3. N/A May 7th, 2006 1:02 am

    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.

  4. PsychoKlown May 7th, 2006 3:46 am

    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.

  5. dave smith May 17th, 2006 6:24 am

    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

  6. admin May 17th, 2006 6:37 am

    Of course you can use it! :)

  7. zekel June 19th, 2006 4:33 am

    very good, had no idea that you could do this :) . thx

  8. […] 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) […]