Force to download .PDF
With some PDF reader software, including the most popular Adobe Acrobat Reader, the default setting is to open PDF files in the browser when we click on a link to a PDF.
As a webmaster you can force the browser dialog box allowing to choose to open it directly or to save it..
First, you must create a small PHP file with that:
<?php
if (file_exists ($_GET['f']))
{
header('Content-type: application/force-download');
header('Content-Disposition: attachment; filename=' . basename ($_GET['f']));
readfile($_GET['f']);
}
else
{
header('HTTP/1.0 404 Not Found');
echo 'Error, this file does not exist.';
}
?>
What does this script? It sends a header saying the browser to force the download for this file, then the name to suggest in the dialog box, and finally it sends the file.
If the file does not exist, it returns a 404 error. The message can be embellished or even included in the design of your site.
I call this file _pdf.php. Then, we must call this file when we put a link to a PDF.
1st case, your server allow URL rewriting
It's the most simple, just add this or create a .htaccess file with this:
RewriteEngine on
RewriteRule ^(.*).pdf$
_pdf.php?f=$1 [L]
Instead of opening a file .pdf directly, it sends it to our _pdf.php file which will force the download.
2d case, your server does not allow address rewriting
That will be more tedious because you must rewrite by hand
your links to PDF. Instead of a link to file.pdf write
_pdf.php?f=file.pdf
If you don't know in what case you are, just try the 1st, if it doesn't work you must choose te second solution.






Thanks.
Saturday 14 February 2009 at 10:34but can i force download a pdf file from external url?
Yes,
with the first version. PHP is generally configured to allow distant readfile().
The 'f' parameter has to be the entire URL:
_pdf.php?f=http://.....
The disadvantage is your server will receive the full PDF and retransfer it, so you will use bandwidth compared to a direct download.
Saturday 14 February 2009 at 16:13