php下curl与file_get_contents性能对比

前言

      php站点没什么访问量,但是负载又出奇的高,反馈给程序员一般就一个结果,代码没有问题,检查一下服务器是不是正常的,有些人就不停的处在扯皮时期了,何不查查问题. 好吧,我这有一例,便是file_get_contents远程url引起的.好,进入正题.

      如下是curl和file_get_contents连接淘宝ip地址库的接口.

php代码

文件:1829.php

<?php
/**
 * 通过淘宝IP接口获取IP地理位置
 * @param string $ip
 * @return: string
 **/
function getCityCurl($ip)
{
    $url="http://ip.taobao.com/service/getIpInfo.php?ip=".$ip;
    $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);

    $ipinfo=json_decode($file_contents);
    if($ipinfo->code=='1'){
        return false;
    }
    $city = $ipinfo->data->region.$ipinfo->data->city;
    return $city;
}

function getCity($ip)
{
    $url="http://ip.taobao.com/service/getIpInfo.php?ip=".$ip;
    $ipinfo=json_decode(file_get_contents($url));
    if($ipinfo->code=='1'){
        return false;
    }
    $city = $ipinfo->data->region.$ipinfo->data->city;
    return $city;
}

// for file_get_contents
$startTime=explode(' ',microtime());
$startTime=$startTime[0] + $startTime[1];
for($i=1;$i<=10;$i++)
{
   echo getCity("121.207.247.202")."</br>";
}
$endTime = explode(' ',microtime());
$endTime = $endTime[0] + $endTime[1];
$totalTime = $endTime - $startTime;
echo 'file_get_contents:'.number_format($totalTime, 10, '.', "")." seconds</br>";

//for curl
$startTime2=explode(' ',microtime());
$startTime2=$startTime2[0] + $startTime2[1];
for($i=1;$i<=10;$i++)
{
   echo getCityCurl('121.207.247.202')."</br>";
}
$endTime2 = explode(' ',microtime());
$endTime2=$endTime2[0] + $endTime2[1];
$totalTime2 = $endTime2 - $startTime2;
echo "curl:".number_format($totalTime2, 10, '.', "")." seconds";
?>


测试

      访问http://test.ttlsa.com/html/1829.php,结果如下图:


php下curl与file_get_contents性能对比
php下curl与file_get_contents性能对比- 图


file_get_contents速度:4.2404510975 seconds
curl速度:2.8205530643 seconds

curl比file_get_contents速度快了30%左右,不过最重要的是服务器负载更低.


禁用url_open

为了防止这一问题,我直接把file_get_contents远程url功能,禁用是最靠谱得选择,口头告知程序员,没效率.

allow_url_fopen = On
改为
allow_url_fopen = Off

替换方法

使用curl替换file_get_contents

总结

     file_get_contents用来读文件就行,不要用它来获取远程url得信息,走api之类得绝对不要考虑它,强烈建议系统管理员禁用url_open. 速度方面curl已经占优,性能上大家自己测试一下就会下决心以后不再使用这么粗劣得函数了.

个人博客:http://www.ttlsa.com/html/1829.html
osc博客:http://my.oschina.net/766/blog/157580

转载于:https://my.oschina.net/766/blog/157580

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值