file_get_contents函数发送User_agent的方法

在用file_get_contents函数采集网站时,有时会遇到明明用浏览器可以看,但就是采不到内容的问题。这很有可能是服务器上做了设置,根据 User_agent判断是否为正常的浏览器请求,默认PHP的file_get_contents函数是不发送ua的,如果要采集这样的网站,我们就要 让PHP模拟浏览器发送UA,这样对方的服务器就会以为我们是用浏览器是浏览,而返回正常的内容。
发送UA方法很简单,在使用file_get_contents函数前加上这一句:

 

 


ini_set('user_agent','Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; GreenBrowser)');
$url='http://www.baidu.com';
echo $flg=@file_get_contents($url);


其中Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; GreenBrowser)是 IE7 WindowsXP GreenBrowser环境下的UA,可根据需要自行修改成其他的,甚至可以伪装蜘蛛。


Baiduspider+(+http://www.baidu.com/search/spider.htm)       百度蜘蛛User_agent
Sosospider+(+http://help.soso.com/webspider.htm)      SOSO蜘蛛User_agent
Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)      GOOGLE蜘蛛User_agent
Mozilla/5.0+(compatible;+Yahoo!+Slurp;+http://help.yahoo.com/help/us/ysearch/slurp)      Yahoo蜘蛛User_agent
Mozilla/5.0 (compatible; YoudaoBot/1.0; http://www.youdao.com/help/webmaster/spider/; )      有道蜘蛛User_agent
posted @ 2010-12-23 15:56  无痕2010  阅读(479)  评论(0编辑  收藏  举报