dongyaoxiu6244
2017-10-27 06:42
浏览 510
已采纳

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

图片转代码服务由CSDN问答提供 功能建议

我正在尝试通过API,实时开放访问pdf文件,然后将该文件下载到我的服务器 。 但是,PDF文件不以“.pdf”扩展名结尾,而是封装在更复杂的网址中: http://aip.scitation.org/doi/pdf/10.1063/1.4996175 网络浏览器只是要求打开或将其保存为PDF文件,而我的脚本无法翻译 因此。 如何让我的PHP脚本将此URL识别为PDF文件? 提前谢谢。 Olivier

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongping9475 2017-10-27 06:50
    已采纳

    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.

    点赞 打赏 评论
  • dqz13288 2017-10-27 06:44

    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.

    点赞 打赏 评论
  • duanhuayong6687 2017-10-27 11:01

    @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!

    点赞 打赏 评论

相关推荐 更多相似问题