首页 > 其他 > 详细

file_get_contents伪造user_agent curl设置useragent的方法

时间:2014-08-26 20:02:26      阅读:323      评论:0      收藏:0      [点我收藏+]

file_get_contents 和 curl 这俩强悍的函数,在远程抓取时候相当有用处.不过一些网站会根据来访ip是否携带user_agent来判断是正常的浏览器客户端还是机器.所以,我们的任务就是给他们伪造user_agent.


file_get_contents伪造user_agent 方法如下:

ini_set(‘user_agent‘,‘Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727;http://www.9qc.com)‘);


curl伪造user_agent的方法:

curl_setopt($c, CURLOPT_USERAGENT, ‘Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727;http://www.9qc.com)‘); 



curl的完整函数方法:

function curl_get_file_contents($URL)   
    {   
        $c = curl_init();   
        curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
//curl_setopt($c, CURLOPT_HEADER, 1);//输出远程服务器的header信息
curl_setopt($c, CURLOPT_USERAGENT, ‘Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727;http://www.9qc.com)‘);
        curl_setopt($c, CURLOPT_URL, $URL);   
        $contents = curl_exec($c);   
        curl_close($c);
        if ($contents) {return $contents;}
            else {return FALSE;}
    }
这样就可以抓取了,user_agent可以自己修改.  


PS: (.*?):后面问号的意思是最少匹配(即懒惰匹配),如果没有那个问号就会最多匹配(即贪婪匹配)。

file_get_contents伪造user_agent curl设置useragent的方法

原文:http://my.oschina.net/JKOPERA/blog/306867

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!