views:

66

answers:

2

I have an anchor tag:

<a href="file.pdf">Download Me</a>

I would like for the user to click on it and then have a Save-As dialog box appear with a new filename I determine.

I found this(http://www.w3schools.com/php/func_http_header.asp):

header("Content-type:application/pdf");

// It will be called downloaded.pdf
header("Content-Disposition:attachment;filename='downloaded.pdf'");

// The PDF source is in file.pdf
readfile("file.pdf");

I don't understand where to put those headers. At the top of the page? When I try to place those 3 lines directly above my link I receive the following errors:

Warning: Cannot modify header information - headers already sent by (output started at /home5/ideapale/public_html/amatorders_basic/admin/download.php:38) in /home5/ideapale/public_html/amatorders_basic/admin/download.php on line 118

I got the same error for both of the header lines I just added. Right after that, there are thousands lines of ASCII letters. How can I get the Save-As dialog box to appear using either jQuery or PHP(whatever is easier)?

A: 

Create a new page with the headers and the readfile, then make the download link refer to the page, which will return the PDF file.

For example:

<a href="download.php?file=file.pdf">Download Me</a>

Source for download.php:

$filename = $_REQUEST['file'];
header("Content-type:application/pdf");
// It will be called downloaded.pdf
header("Content-Disposition:attachment;filename='$filename'");

// The PDF source is in file.pdf
readfile($filename);
Stijn Van Bael
+3  A: 

Please be careful when using Stijn Van Bael's code, it opens you up to some serious security exploits.

Try something like:

--- download.php ---
$allowed_files = array('file.pdf', 'otherfile.pdf');

if (isset($_REQUEST['file']) && in_array($_REQUEST['file'], $allowed_files))
{
  $filename = $_REQUEST['file'];

  header("Content-type:application/pdf");
  header("Content-Disposition:attachment;filename='$filename'");

  // The PDF source is in file.pdf
  readfile($filename);

  exit();
}
else
{
  // error
}


--- linkpage.php ---
<a href="download.php?file=file.pdf">Download PDF</a>
<a href="download.php?file=otherfile.pdf">Download PDF</a>

Probabaly a better way to do this is at the web server level (this can go in .htaccess) This will force all PDF's to be treated as a binary file (forcing the browser to download them) in and below the directory you put this in.

<FilesMatch "\.(?i:pdf)$">
 Header set Content-Disposition attachment
 ForceType application/octet-stream
</FilesMatch>
Kieran Allen