dongyaoxiu6244
dongyaoxiu6244
2017-10-27 06:42

PHP - 从链接下载pdf文件并保存在本地文件夹中

已采纳

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

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • dongping9475 dongping9475 4年前

    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.

    点赞 评论 复制链接分享
  • duanhuayong6687 duanhuayong6687 4年前

    @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
    " .
                  "User-Agent: Mozilla/5.0 (Windows NT 6.0; rv:8.0) Gecko/20100101 Firefox/8.0
    " .
                  "Cookie: foo=bar
    "
      )
    ));
    

    Many thanks!

    点赞 评论 复制链接分享
  • dqz13288 dqz13288 4年前

    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.

    点赞 评论 复制链接分享