检查PHP cURL服务器响应中的头 [英] Check headers in PHP cURL server response

查看:152
本文介绍了检查PHP cURL服务器响应中的头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've been using PHP curl to get data I need from remote website. Here is the cURL function I used:

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

但是如何获得响应的头文件?

But how do I get the headers for the response?

推荐答案

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

If my comment above is correct, change:

curl_setopt($ch, CURLOPT_HEADER, 0);

到:

curl_setopt($ch, CURLOPT_HEADER, 1);

并解析返回的标题,不过您认为合适。请注意,只要在函数中更改上述内容,就会返回标头的内容,因此,如果您只需要只返回标头:

and parse the returned headers out however you see fit. Note that just changing the above in your function will return both headers and content, so if you want only headers returned:

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);
}

这篇关于检查PHP cURL服务器响应中的头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆