17

Possible Duplicate:
open download dialog with php

I have a link in my page say, <a href='test.pdf'>(Test.pdf)</a>. When I click on that link, download dialogue box should open to download that file. Can anyone help me in implementing this in PHP?

thanks

2

3 Answers 3

44
$filename = 'Test.pdf'; // of course find the exact filename....        
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private', false); // required for certain browsers 
header('Content-Type: application/pdf');

header('Content-Disposition: attachment; filename="'. basename($filename) . '";');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($filename));

readfile($filename);

exit;

Name the above file as download.php

HTML:

<a href="download.php">Test.pdf</a>

That should do it.

3
  • the downloaded pdf file doesnt open it says the file is not decoded correctly? Commented Dec 11, 2012 at 12:32
  • @JacobRelkin Quick question. Can you pass in arguments? Like download.php?filecode=1234 and use those to fill in the header functions? or do the headers have to be called before any other call. Example: $filename = $_get['filecode'] Commented Oct 4, 2016 at 13:08
  • 1
    @Caperneoignis: Might be too late, but yes it is possible. just make sure the characters you pass on the $_GET variable are URL friendly or do the encode-decode process.
    – Elymentree
    Commented Dec 23, 2016 at 16:20
14
<a href="test.pdf">test.pdf</a>
1
  • Simplex sigillum veri. IMO this should be the accepted answer :-) Commented Nov 16, 2023 at 14:25
3

In the case of a PDF file, most browsers are going to look for the helper (acrobat) to load it in your browser by default. You are trying to get around this default behavior is my guess.

The easiest way to do this (assuming you're on *nix box with apache) is to make an .htaccess file in the directory you want to have this result and add the line:

AddType application/octet-stream .pdf

This will cause any file with the extention .pdf to download by default. You can even have some .pdf files on the page load in the browser while others download by using the FilesMatch directive ( http://www.askapache.com/htaccess/using-filesmatch-and-files-in-htaccess.html ).

I realize your original question said "how do I do it with PHP" but I thought I'd post in case you were looking for a simpler, more elegant solution. Do keep in mind any directives you put in an .htaccess file will also affect any sub-directories below it.

Not the answer you're looking for? Browse other questions tagged or ask your own question.