Jump to content
Larry Ullman's Book Forums

Force Download A Pdf


Recommended Posts

Hello,

 

I need to force download a PDF file instead of displaying it in the browser, any idea how I'd do this?

 

This is what I've tried:

 

      $file = 'file.pdf';
       header('Content-type: application/pdf');
       header ("Content-type: octet/stream");
       header ("Content-disposition: attachment; filename=".$file.";");
       header("Content-Length: ".filesize($file));
       readfile($file);
       exit;

 

This appears to force the download, but when I try to open it I'm told that it's either empty or can't be read. Any ideas?

 

Thanks,

 

Jon

Link to comment
Share on other sites

You need to set some special headers in the page, instead of just a link to the URL of the document:

 

header ("Content-Type: application/pdf");
header ("Content-Disposition: attachment; filename=\"$filename\"");  // $filename is the name of the file
header ("Content-Length: $filesize");  // $filesize is derived by using filesize() on the file
header ("Content-Transfer-Encoding: binary");
readfile ($location);  // $location is the URL, including filename, of the file

This should present the user with a dialog box that asks them whether they want to open or save the file.

  • Upvote 2
Link to comment
Share on other sites

 Share

×
×
  • Create New...