HMV.co.in

September 22, 2008

Force download for PDF, JPG, GIF directly from the web browser

Filed under: php — Tags: , , , — Harsha M V @ 6:19 pm

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:

<?php
$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!

Direct to Download Images and PDFs

Filed under: php — Tags: , , — Harsha M V @ 5:43 pm
PDF for direct download

PHP

<?php
header
('Content-Type:application/pdf');
header
('Content-Disposition:attachment;filename=download_pdf.pdf');
readfile
('original.pdf');
?>

And then modified it to do it with an image

PHP

<?php
header
('Content-Type:image/jpeg');
header
('Content-Disposition:attachment;filename=download_image.jpg');
readfile
('original.jpg');
?>

Blog at WordPress.com.