There are a couple of solutions suggested all around the Web, one of them being to give a user choice between saving file locally or open it in Adobe Reader window. One of the ways to do it is changing MIME type of the .pdf file and Content-Disposition header. Instead of default application/pdf we would be serving more generic application/octet-stream. Content-Disposition header has to be set as attachment. Here is an example PHP script which sends any existing .pdf file from the script's directory:
Even though it works, it is not very elegant. We might want to link directly to .pdf documents instead of pdf.php?file=document.pdf and serve the files transparently through the php script.$file = $_GET['file'] . '.pdf';
if (preg_match('/^[a-zA-Z0-9_\-]+\.pdf$/', $file)
&& file_exists($file)) {
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $file);
readfile($file);
} else {
header("HTTP/1.0 404 Not Found");
}
For Apache users it is quite easy to achieve. An example .htaccess file:
A few words of explanation:RewriteEngine On
RewriteBase /your.directory.with.documents/pdf
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^(.+)\.pdf$ ./pdf.php?file=$1 [L,NC,QSA]
- Third line says to redirect to pdf.php script only valid requests for existing files.
- Fourth line rewrites requests for .pdf files only as this is all we are interested in. The script gets filename without extension, eg. "document.pdf" is passed to the script as "document".
- More about rewrite_mod for apache you can find in the documentation.