dongxi5423 2019-08-02 14:43
浏览 479

如何从url使用php cURL下载pdf?

Hi I am trying to download the following file with PHP (I want to download it every day): http://www.borkumer-zeitung.de/wp-content/uploads/Zeitung/2019/08/BZ_020819.pdf

When I enter the url in my browser I can open the PDF just fine. But when I try to download it using cURL I get redirected to a login page.

I tried different settings for curl_setopt but nothing seems to work. The code works but instead of downloading the pdf I get redirected to: http://www.borkumer-zeitung.de/anmelden/ and the content of this page is downloaded.

This is my code: 

$url = "http://www.borkumer-zeitung.de/wp-content/uploads/Zeitung/2019/08/BZ_020819.pdf";
$saveTo = "newspaper/newspaper.pdf";


//Open file handler.
$fp = fopen($saveTo, 'w+');

//If $fp is FALSE, something went wrong.
if($fp === false){
    throw new Exception('Could not open: ' . $saveTo);
}


//Create a cURL handle.
$ch =curl_init($url);

curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0');
curl_setopt($ch, CURLOPT_REFERER, 'http://www.borkumer-zeitung.de/3d-flip-book/02-08-2019/');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
//Pass our file handle to cURL.
curl_setopt($ch, CURLOPT_FILE, $fp);

//Timeout if the file doesn't download after 20 seconds.
curl_setopt($ch, CURLOPT_TIMEOUT, 20);

//Execute the request.
curl_exec($ch);

//If there was an error, throw an Exception
if(curl_errno($ch)){
    throw new Exception(curl_error($ch));
}

//Get the HTTP status code.
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

//Close the cURL handler.
curl_close($ch);

//Close the file handler.
fclose($fp);

if($statusCode == 200){
    echo 'Downloaded!';
} else{
    echo "Status Code: " . $statusCode;
}

I would love to get a hint or the solution to be able to download this file on my server :)

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
    • ¥15 求daily translation(DT)偏差订正方法的代码
    • ¥15 js调用html页面需要隐藏某个按钮
    • ¥15 ads仿真结果在圆图上是怎么读数的
    • ¥20 Cotex M3的调试和程序执行方式是什么样的?
    • ¥20 java项目连接sqlserver时报ssl相关错误
    • ¥15 一道python难题3
    • ¥15 牛顿斯科特系数表表示
    • ¥15 arduino 步进电机
    • ¥20 程序进入HardFault_Handler