PHP使用curl替代file_get_contents
2014-03-23 00:00
549 查看
初学php的朋友们,很容易翻一个错误,在写采集程序或者调用api接口总会有线考虑到使用file_get_contents函数来或许内容,程序的访问量不大倒是没什么影响,但是访问量提升了那非常的悲剧了,你会发现服务器负载飙升,最后服务器宕机.初入公司便遇到这个问题,遂使用curl取代此命令,并且禁用远程file_get_contents,它支持很多协议:FTP, FTPS, HTTP, HTTPS, GOPHER, TELNET, DICT, FILE 以及 LDAP.
curl替代file_get_contents[/caption] 福建省福州市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%性能差距.
淘宝IP库使用方法打开连接 转载请注明出处:http://www.ttlsa.com/html/1821.html
<?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对比结果. [caption id="attachment_1827" align="aligncenter" width="626"]
curl替代file_get_contents[/caption] 福建省福州市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%性能差距.
淘宝IP库使用方法打开连接 转载请注明出处:http://www.ttlsa.com/html/1821.html
相关文章推荐
- PHP使用curl替代file_get_contents
- PHP使用curl替代file_get_contents
- PHP使用curl替代file_get_contents
- PHP使用curl替代file_get_contents
- php中使用Curl、socket、file_get_contents三种方法POST提交数据
- PHP无法使用file_get_contents或者curl_init()函数解决办法
- PHP中curl_init和file_get_contents配合使用
- php采用file_get_contents代替使用curl实例
- php中使用Curl、socket、file_get_contents三种方法POST提交数据
- windows nginx使用file_get_contents、fopen、curl访问php文件造成阻塞的解决办法
- php中使用Curl、socket、file_get_contents三种方法POST提交数据
- 使用PHP的curl扩展实现跨域post请求,以及file_get_contents()百度短网址例子
- php中使用Curl、socket、file_get_contents三种方法POST提交数据
- nginx+fastcgi php 使用file_get_contents、curl、fopen读取localhost本站点.php异常的情况
- PHP使用file_get_contents或curl请求https的域名内容为空或Http 505错误的问题排查方法
- php采用file_get_contents代替使用curl实例
- file_get_contents("php://input")的使用方法
- file_get_contents("php://input")的使用方法
- php 模拟浏览器 发送 post 和 get 请求(兼容curl + file_get_contents)
- php中file_get_contents与curl性能比较分析