【问题标题】:get ONLY the http status code with curl and php仅使用 curl 和 php 获取 http 状态代码
【发布时间】:2015-11-12 17:13:03
【问题描述】:

我试图只获取三位数的 http 状态码,变量 $response 仅此而已。例如 302、404、301 等等。我在我的代码中注意到的另一个观察结果是在一些网站上,例如谷歌,它正在下载似乎是身体一部分的东西,这是对带宽的巨大浪费并且速度很慢。

<?php

$URL  = 'http://www.google.com';
$curlHandle = curl_init();
curl_setopt($curlHandle, CURLOPT_URL, $URL);
curl_setopt($curlHandle, CURLOPT_HEADER, true);
$response = curl_exec($curlHandle);
echo $response;  
?>

【问题讨论】:

    标签: php curl


    【解决方案1】:

    您可以将CURLOPT_NOBODY 选项设置为不接收正文。然后你可以通过curl_getinfo获取状态码。

    像这样:

    <?php
    
    $URL  = 'http://www.google.com';
    $curlHandle = curl_init();
    curl_setopt($curlHandle, CURLOPT_URL, $URL);
    curl_setopt($curlHandle, CURLOPT_HEADER, true);
    curl_setopt($curlHandle, CURLOPT_NOBODY  , true);  // we don't need body
    curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
    curl_exec($curlHandle);
    $response = curl_getinfo($curlHandle, CURLINFO_HTTP_CODE);
    curl_close($curlHandle); // Don't forget to close the connection
    
    echo $response,""; 
    ?>
    

    【讨论】:

      【解决方案2】:

      首先,您只获得标题 (CURLOPT_NOBODY)。

      然后您捕获 HTML 作为结果 (CURLOPT_RETURNTRANSFER)。

      最后,您使用正则表达式提取 HTTP 代码,该正则表达式获取由空格包围的第一个数字。

      $URL  = 'http://www.google.com';
      $curlHandle = curl_init();
      curl_setopt($curlHandle, CURLOPT_URL, $URL);
      curl_setopt($curlHandle, CURLOPT_NOBODY, true);
      curl_setopt($curlHandle, CURLOPT_HEADER, true);
      curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
      $response = curl_exec($curlHandle);
      preg_match('/ \d+ /', $response, $matches);
      $response = $matches[0];
      

      【讨论】:

        【解决方案3】:

        你可以使用这个状态码:

        function getStatusCode($url) {
           $headers = get_headers($url);
           preg_match('/\s(\d+)\s/', $headers[0], $matches);
           return $matches[0];
         }
        
         echo getStatusCode('http://www.google.com');
        

        http://php.net/manual/en/function.get-headers.php

        【讨论】:

        • 我在尝试使用 get_headers 函数时收到一个漂亮的警告。你认为为什么会这样?
        • @Amarnasan 警告说什么?
        • 没有别的了吗?使用 $url = 'google.com'?但是状态码还是返回了?
        • 没有别的,而且我根本没有状态码。即使我用“@”跳过错误,我什么也得不到。
        • @Amarnasan 好的,我也找到了这个例子:php.net/manual/en/function.get-headers.php#97684 对不起,没有更多的错误细节,我无法帮助你。
        猜你喜欢
        • 2012-08-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-30
        • 2017-09-12
        相关资源
        最近更新 更多