file_get_contents 函数添加超时设置
在PHP实际开发中很多时候我们都会用到 file_get_contents 这个 函数来获取远程页面返回的内容 ,但是如果远程响应时间很慢的话 ,file_get_contents() 就会一直卡在那儿,不会超时,这时候我们有时候会发现Web服务的 Linux 服务器,突然系统负载上升,使用 top 命令查看,很多 php-cgi 进程 CPU 使用率接近100%。
?
我们知道,在 php.ini 中,有一个参数 max_execution_time 可以设置 PHP 脚本的最大执行时间,但是,在 php-cgi(php-fpm) 中,该参数不会起效。真正能够控制 PHP 脚本最大执行时间的是 php-fpm.conf 配置文件中的以下参数:
<?php$ctx = stream_context_create(array( 'http' => array( 'timeout' => 1 //设置一个超时时间,单位为秒 ) ));file_get_contents("http://example.com/", 0, $ctx);?>?
遇到问题的童鞋们 你们可以去试试。。。