使用 file_get_contents 获取网站信息报错failed to open stream: HTTP request failed!

使用 filegetcontents 获取网站信息报错failed to open stream: HTTP request failed!

当使用php5自带的filegetcontents方法来获取远程文件的时候,有时候会出现filegetcontents(): failed to open stream: HTTP request failed!这个警告信息。

google或者baidu一下,好多这样的问题,解决的方法都是修改php.ini,把allowurlfopen给启用,改成 allowurlfopen = On

这样做可以解决某些人的问题,有人说在php.ini中,有这样两个选项:allowurlfopen =on(表示可以通过url打开远程文件),user_agent="PHP"(表示通过哪种脚本访问网络,默认前面有个 " ; " 去掉即可。)重启服务器。

但是有些还是会有这个警告信息,想用完美的解决还差一步,还得设置php.ini里面的useragent,php默认的useragent是 PHP,我们把它改成Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)来模拟浏览器就可以了

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

在用filegetcontents函数采集网站时,有时会遇到明明用浏览器可以看,但就是采不到内容的问题。这很有可能是服务器上做了设置,根据 Useragent判断是否为正常的浏览器请求,默认PHP的filegetcontents函数是不发送ua的,如果要采集这样的网站,我们就要 让PHP模拟浏览器发送UA,这样对方的服务器就会以为我们是用浏览器是浏览,而返回正常的内容。 发送UA方法很简单,在使用fileget_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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值