Friday 26 Sep

Force to download .PDF

PHPWith 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 :arrow: _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.


Voted 0  

3 answers at “Force to download .PDF”

  1. 1
    Canon said:

    Thanks.
    but can i force download a pdf file from external url?

  2. 2
    David said:

    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.

  3. 3
    California Drug Rehab said:

    Wow. This Blog is truly a gold mine. I will actually try these tips and let you know how they work out! Thanks again mate.

Leave a comment

I follow

© Azure Dev Computer news & PHP tutorials Theme from Greenline + PHP HTML

ThemeWordpress
Azure Dev