Forcing browsers to download, not open, .pdf documents
Tags: php
Date: 19th November, 2009
Unfortunately, the default installation of Adobe Reader insists that .pdf documents open up a version of Reader in the browser. This can be useful but it isn’t always what you want, particularly as a large .pdf uses a lot of computing resources. What we did was create a link to a small PHP script which tells the browser to download the file rather than open it. I’m not going to take the credit for the script, because it isn’t mine (although, let’s face it, it’s not that difficult…), but I can’t remember where I found it. The script looks like so:
<?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.’;
}
?>
It’s not an ideal solution, mind, because you can’t simply link to the .pdf document. Instead you have to link to the script and pass the document as the variable f, for example:
<a href=”forcedownloadscript.php?f=thisdocument.pdf”>This document</a>
…then the script will force the browser to open the document as a download rather than by opening Adobe Reader. Almost excellent!