【问题标题】:PHP Curl get server response [duplicate]PHP Curl获取服务器响应[重复]
【发布时间】:2013-01-08 09:03:02
【问题描述】:

可能重复:
Easy way to test a URL for 404 in PHP?

我正在使用 curl 从 PHP 后端下载一系列 pdf。我不知道序列什么时候结束,比如 1.pdf、2.pdf……等等。

以下是我用来下载 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);

但是我如何确定该 pdf 在后端不存在?找不到文件时 curl 是否返回任何响应?

【问题讨论】:

    标签: php


    【解决方案1】:
    $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);
    

    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true); 成功时返回结果,失败时返回 FALSE。

    curl_setopt($ch,CURLOPT_RETURNTRANSFER,false); 成功时返回 TRUE,失败时返回 FALSE。

    另外,对于file not found

    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if($http_code == 404)
    {
      /*file not found*/
    }
    

    【讨论】:

    • 谢谢! curl_getinfo($url, CURLINFO_HTTP_CODE) 解决了我的问题。
    【解决方案2】:

    只测试$data = curl_exec($ch);之后http响应的statut代码

    $http_status = curl_getinfo($url, CURLINFO_HTTP_CODE);
    if($http_status == '404') {
    
       //not found, -> file doesnt exist in your backend
    }
    

    更多信息here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-26
      • 2017-06-18
      • 1970-01-01
      • 1970-01-01
      • 2015-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多