检查PHP cURL服务器响应中的标头

时间:2012-12-13 14:21:26

标签: php curl

我一直在使用PHP curl从远程网站获取我需要的数据。这是我使用的cURL函数:

function get_content($adr)  
    {  
       $ch = curl_init();  

       curl_setopt ($ch, CURLOPT_URL, $adr);  
       curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
       curl_setopt ($ch, CURLOPT_HEADER, 0);  

       ob_start();  

       curl_exec ($ch);  
       curl_close ($ch);  
       $string = ob_get_contents();  

       ob_end_clean();  

       return $string;      

    }  
$myrul = "http://remoteurl.com";
$result = get_content($myrul);

但是如何获取响应的标题?

1 个答案:

答案 0 :(得分:3)

如果我上面的评论是正确的,请更改:

curl_setopt($ch, CURLOPT_HEADER, 0);

为:

curl_setopt($ch, CURLOPT_HEADER, 1);

然后解析返回的标题,但是你觉得合适。请注意,只需更改功能中的上述内容即可返回标题内容,因此如果您希望仅返回 标题:

function http_head_curl($url,$timeout=10)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); // in seconds
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_NOBODY, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $res = curl_exec($ch);
    if ($res === false) {
        throw new RuntimeException("cURL exception: ".curl_errno($ch).": ".curl_error($ch));
    }
    return trim($res);
}