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

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

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

可能重复:
在PHP中测试404的URL的简便方法? < / p>

我正在使用curl从PHP的后端下载一系列pdf。 我不知道序列何时结束如1.pdf,2.pdf ......等。

以下是我用来下载pdf的代码:

  $ url ='http://&lt; ip&gt; .pdf'; 
 $ path =“C:\\ test.pdf”; 
 
 $ fp = fopen(  $ path,'w'); 
 
 $ ch = curl_init($ url); 
 curl_setopt($ ch,CURLOPT_FILE,$ fp); 
 
 $ data = curl_exec($ ch); 
 \  n fclose($ fp); 
   
 
 

但是如何确定后端中不存在该pdf? 当找不到文件时,curl会返回任何响应吗?

在此先感谢

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

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条)

相关推荐 更多相似问题