OTroccaz
OTroccaz

Reputation: 3

PHP - download pdf file from link and save in local file folder

I am trying to get through an API, a live open access pdf file, and then download that file to my server. However the PDF file does not end with a ".pdf" extension but is encapsulated in a more complexe url: http://aip.scitation.org/doi/pdf/10.1063/1.4996175 A web browser would simply ask to open or save it as a PDF file, whereas my script cannot translate it as such. How can I make my PHP script recognize this url as a PDF file? Thanks in advance. Olivier

Upvotes: 0

Views: 11641

Answers (3)

Oleg Loginov
Oleg Loginov

Reputation: 347

It is not clear what exactly you are doing and why your php script has to recognize pdf.

If you are loading the file by your php application - you can check content type header of the file, which contains file type information along with the extension. You can use http://php.net/manual/en/book.curl.php library for it.

If you want to let users download the file on your site - you have to set correct content type like this:

header('Content-Type: application/pdf');

Now the browser will know that the file you are serving is pdf even without extension.

Update

Eventually it turned out that the site with pdf files just required some cookies, as described below.

Upvotes: 1

OTroccaz
OTroccaz

Reputation: 3

@Oleg Loginov, you are right : just adding a cookie in the context, and the PDF is well uploaded via a copy command.

$context = stream_context_create(array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n" .
              "User-Agent: Mozilla/5.0 (Windows NT 6.0; rv:8.0) Gecko/20100101 Firefox/8.0\r\n" .
              "Cookie: foo=bar\r\n"
  )
));

Many thanks!

Upvotes: 0

Himanshu Upadhyay
Himanshu Upadhyay

Reputation: 6565

You can do like this:

<a href="http://aip.scitation.org/doi/pdf/10.1063/1.4996175" download="sample.pdf" id="pdf_file">Download PDF</a>

If you want to do the auto download without showing the anchor tag on page, then you can set JavaScript or Jquery code. To do this, set display:none; to the anchor tag and then you can trigger click event using jquery like this:

$(document).ready(function(){
    $('#pdf_file').trigger('click');
};)

So it will start downloading the file when page loads.

If you want to grab the file and store it on your server then you can do that using this:

file_put_contents("sample.pdf",file_get_contents("URL"));

You can use absolute path instead just file name and you would get the file stored at the defined folder of your server.

Upvotes: 1

Related Questions