2

i need to make a link downloadable to PDF, the solution can be in Javascript, HTML or PHP.

Things you have to know to answer this question:

1- I tried add the attribute "download" in and its only works in chrome

2- I don't have the pdf file in my server, i only have a link

3- The name of the file change because the link is generated dynamically

4- I don't want the pdf open in the browser in another tab and i don't want to open in the same page. Only download.

EDIT:

5 -i don't want to open a page and start to download i need to wait the user click to do that

2 Answers2

1

Try this:

<?php
header("Content-disposition: attachment; filename=document.pdf");
header("Content-type: application/pdf");
readfile("document.pdf");
?>

Credits: http://webdesign.about.com/od/php/ht/force_download.htm

Craziest Hacker
  • 99
  • 3
  • 12
  • This will actually often open the PDF in the browser, because of the `content-type: application/pdf`, so switching that out with `application/octet-stream` would do the trick. – Emil Ingerslev May 07 '15 at 05:53
  • @EmilIngerslev: You can verify with a similar code here: [link](http://webdesign.about.com/od/php/ht/force_download.htm) – Craziest Hacker May 07 '15 at 05:57
  • @EmilIngerslev — No, it won't. Content-disposition: attachment will cause it to download the file. You don't need to lie about the content-type. – Quentin May 07 '15 at 08:08
  • the problem with this approach is that the file is a URL on another server, so it ends up being pretty expensive (in terms of bandwith) and slow. – Quentin May 07 '15 at 08:09
  • That will work in those browsers/systems that respect the attachment header, but through experience I've seen that it isn't always the case. The other header, not specifying it's a pdf, but just a download works, even in old browsers. – Emil Ingerslev May 07 '15 at 13:01
  • @Quentin Have you checked out the other SO on almost the same issue?: http://stackoverflow.com/questions/7263923/how-to-force-file-download-with-php – Emil Ingerslev May 07 '15 at 13:03
0

You can solve this with the following PHP script:

$file_url = 'http://www.myremoteserver.com/file.exe';
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary"); 
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\""); 
readfile($file_url); // do the double-download-dance (dirty but worky)

credits: How to force file download with PHP

Community
  • 1
  • 1
Emil Ingerslev
  • 4,645
  • 2
  • 24
  • 18