Some tricks

Tricks for web designers and developers

Archive for the 'HTML' Category

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