用curl 代替file_get_contents 解决获取网络资源的超时问题

初学php的朋友们,很容易翻一个错误,在写采集程序或者调用api接口总会有线考虑到使用file_get_contents函数来或许内容,程序的访问量不大倒是没什么影响,但是访问量提升了那非常的悲剧了,你会发现服务器负载飙升,最后服务器宕机.初入公司便遇到这个问题,遂使用curl取代此命令,并且禁用远程file_get_contents,它支持很多协议:FTP, FTPS, HTTP, HTTPS, GOPHER, TELNET, DICT, FILE 以及 LDAP.

<?php
$url='http://www.baidu.com';

$ch = curl_init();

$timeout = 5;
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);

echo $file_contents;

//function_exists()替换

if(function_exists('file_get_contents')) {
$file_contents = file_get_contents($url);
} else {
$ch = curl_init();
$timeout = 5;
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);
}
return $file_contents;
?>

禁用file_get_contents方法:
打开php.ini,配置如下:

allow_url_fopen = On
改为
allow_url_fopen = Off

如果是fastcgi重启php-fpm,如果是apache+php那直接重启apache即可.

file_get_contents与curl对比结果.


file_get_contents与curl对比结果.

file_get_contents

curl替代file_get_contents

福建省福州市file_get_contents:0.4679060000 seconds
福建省福州市curl:0.3150200000 seconds

这边分别使用file_get_contents与curl使用淘宝ip库来获取IP地址信息,可以发现file_get_contents和curl性能的差距还是比较大.file_get_contents耗时0.467秒,curl使用0.315秒.差了0.152秒,有30%性能差距


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值