|
PHP的file_get_contents在等待返回的时候会一直占用CPU时间。
curl有curlopt_connecttimeout可设,fsockopen有$timeout可设,而file_get_contents和fopen在打开url时,都不可设置响应时间timeout。如果url长时间没有响应,file_get_contents 会跳过短时间内没有响应的,而fopen会一直停留着等待,那么服务器就很可能挂了。
file_get_contents设置timeout的两种方法:
第一种方法:
1 <?php
2 $url = 'http://www.baidu.com';
3 $timeout = 10;//等待10秒
4 $old_timeout = ini_get('default_socket_timeout');
5 ini_set('default_socket_timeout',$timeout);
6 $contents = file_get_contents($url);
7 ini_set('default_socket_timeout',$old_timeout);
8 ?>
第二种方法:
1 <?php
2 $url = 'http://www.baidu.com';
3 $ctx = stream_context_create(array(
4 'http' => array(
5 'timeout'=>10//等待10秒
6 )
7 )
8 );
9 echo file_get_contents($url,0,$ctx);
10 ?>
|
|
|