douweng7308 2013-01-24 14:54
浏览 17
已采纳

PHP Curl获取服务器响应[重复]

Possible Duplicate:
Easy way to test a URL for 404 in PHP?

I am using curl to download a sequence of pdfs from the backend in PHP. I do not know when the sequence ends like 1.pdf, 2.pdf......etc.

Below is the code I am using to download pdf:

$url  = 'http://<ip>.pdf';
    $path = "C:\\test.pdf";

    $fp = fopen($path, 'w');

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_FILE, $fp);

    $data = curl_exec($ch);

    fclose($fp);

But how do I determine that that pdf do not exists in the backend? Does curl returns any response when file not found?

Thanks In Advance

  • 写回答

2条回答 默认 最新

  • doujia7094 2013-01-24 15:03
    关注
    $ch=curl_init("www.example.org/example.pdf");
    curl_setopt($ch,CURLOPT_HEADER,0);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    $result=curl_exec($ch);
    curl_close($ch);
    

    with curl_setopt($ch,CURLOPT_RETURNTRANSFER,true); it will return the result on success, FALSE on failure.

    with curl_setopt($ch,CURLOPT_RETURNTRANSFER,false); it will return TRUE on success or FALSE on failure.

    Moreover, for file not found:

    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if($http_code == 404)
    {
      /*file not found*/
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮