【问题标题】:Getting HTTP code in PHP using curl使用 curl 在 PHP 中获取 HTTP 代码
【发布时间】:2012-08-01 14:49:36
【问题描述】:

我正在使用 CURL 来获取站点的状态,如果它是向上/向下或重定向到另一个站点。我想让它尽可能精简,但效果不佳。

<?php
$ch = curl_init($url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_TIMEOUT,10);
$output = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

return $httpcode;
?>

我把它封装在一个函数中。它工作正常,但性能不是最好的,因为它会下载整个页面,如果我删除$output = curl_exec($ch);,它会一直返回0

有谁知道如何让性能更好?

【问题讨论】:

    标签: php performance curl http-headers


    【解决方案1】:

    首先确定 URL 是否有效(字符串,不为空,语法良好),这样可以快速检查服务器端。例如,首先这样做可以节省大量时间:

    if(!$url || !is_string($url) || ! preg_match('/^http(s)?:\/\/[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(\/.*)?$/i', $url)){
        return false;
    }
    

    确保只获取标题,而不是正文内容:

    @curl_setopt($ch, CURLOPT_HEADER  , true);  // we want headers
    @curl_setopt($ch, CURLOPT_NOBODY  , true);  // we don't need body
    

    有关获取 URL 状态 http 代码的更多详细信息,请参阅我发布的另一篇文章(它也有助于以下重定向):


    整体而言:

    $url = 'http://www.example.com';
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HEADER, true);    // we want headers
    curl_setopt($ch, CURLOPT_NOBODY, true);    // we don't need body
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_TIMEOUT,10);
    $output = curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    echo 'HTTP code: ' . $httpcode;
    

    【讨论】:

    • 我编辑了您的帖子并粘贴了整个工作示例代码。我觉得这种方式更有帮助。顺便说一句,+1 提到 CURLOPT_HEADER 和 CURLOPT_NOBODY 设置! :)
    • 不需要将 CURLOPT_HEADER 设置为 true。无论哪种方式,您仍然可以从 curl_getinfo() 获取 httpcode。
    • 从 PHP 5.5.0 和 cURL 7.10.8 开始,这个 [CURLINFO_HTTP_CODE] 是 CURLINFO_RESPONSE_CODE 的旧别名 (ref)
    • 由于某种原因,这条线 curl_setopt($ch, CURLOPT_NOBODY, true); 挂起。不确定这是否与服务器的 PHP 版本有关。
    【解决方案2】:
    // must set $url first....
    $http = curl_init($url);
    // do your curl thing here
    $result = curl_exec($http);
    $http_status = curl_getinfo($http, CURLINFO_HTTP_CODE);
    curl_close($http);
    echo $http_status;
    

    【讨论】:

    • 这个不需要忽略正文,只需拨打一个电话,这也是我的首选答案。
    • 2021年检查文档:As of PHP 5.5.0 and cURL 7.10.8, this is a legacy alias of CURLINFO_RESPONSE_CODE
    【解决方案3】:
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($ch, CURLOPT_TIMEOUT, 20);
    $rt = curl_exec($ch);
    $info = curl_getinfo($ch);
    echo $info["http_code"];
    

    【讨论】:

      【解决方案4】:

      试试 PHP 的“get_headers”函数。

      类似的东西:

      <?php
          $url = 'http://www.example.com';
          print_r(get_headers($url));
          print_r(get_headers($url, 1));
      ?>
      

      【讨论】:

      • 获取标头比 curl 慢。
      【解决方案5】:

      curl_getinfo — 获取有关特定转移的信息

      查看curl_getinfo

      <?php
      // Create a curl handle
      $ch = curl_init('http://www.yahoo.com/');
      
      // Execute
      curl_exec($ch);
      
      // Check if any error occurred
      if(!curl_errno($ch))
      {
       $info = curl_getinfo($ch);
      
       echo 'Took ' . $info['total_time'] . ' seconds to send a request to ' . $info['url'];
      }
      
      // Close handle
      curl_close($ch);
      

      【讨论】:

        【解决方案6】:

        curl_exec 是必需的。尝试CURLOPT_NOBODY 不下载正文。那可能会更快。

        【讨论】:

          【解决方案7】:

          使用此 hitCurl 方法获取所有类型的 api 响应,即 Get / Post

                  function hitCurl($url,$param = [],$type = 'POST'){
                  $ch = curl_init();
                  if(strtoupper($type) == 'GET'){
                      $param = http_build_query((array)$param);
                      $url = "{$url}?{$param}";
                  }else{
                      curl_setopt_array($ch,[
                          CURLOPT_POST => (strtoupper($type) == 'POST'),
                          CURLOPT_POSTFIELDS => (array)$param,
                      ]);
                  }
                  curl_setopt_array($ch,[
                      CURLOPT_URL => $url,
                      CURLOPT_RETURNTRANSFER => true,
                  ]);
                  $resp = curl_exec($ch);
                  $statusCode = curl_getinfo($ch,CURLINFO_HTTP_CODE);
                  curl_close($ch);
                  return [
                      'statusCode' => $statusCode,
                      'resp' => $resp
                  ];
              }
          

          测试api的演示函数

           function fetchApiData(){
                  $url = 'https://postman-echo.com/get';
                  $resp = $this->hitCurl($url,[
                      'foo1'=>'bar1',
                      'foo2'=>'bar2'
                  ],'get');
                  $apiData = "Getting header code {$resp['statusCode']}";
                  if($resp['statusCode'] == 200){
                      $apiData = json_decode($resp['resp']);
                  }
                  echo "<pre>";
                  print_r ($apiData);
                  echo "</pre>";
              }
          

          【讨论】:

            【解决方案8】:

            这是我的解决方案,需要获取 Status Http 以定期检查服务器状态

            $url = 'http://www.example.com'; // Your server link
            
            while(true) {
            
                $strHeader = get_headers($url)[0];
            
                $statusCode = substr($strHeader, 9, 3 );
            
                if($statusCode != 200 ) {
                    echo 'Server down.';
                    // Send email 
                }
                else {
                    echo 'oK';
                }
            
                sleep(30);
            }
            

            【讨论】:

            • Getheaders 比 curl 慢。
            • 为什么不使用 cron 或 webhook 而不是使用 sleep 和无限循环?
            猜你喜欢
            • 1970-01-01
            • 2017-08-31
            • 2011-04-05
            • 2011-08-13
            • 1970-01-01
            • 1970-01-01
            • 2012-04-01
            相关资源
            最近更新 更多