curl有curlopt_connecttimeout可設,fsockopen有$timeout可設,而file_get_contents和fopen在打開url時,都不可設置響應時間timeout。如果url長時間沒有響應,file_get_contents 會跳過短時間內沒有響應的,而fopen會一直停留着等待,那麼您的服務器就很可能掛了。
file_get_contents設置timeout的兩種方法:
第一種方法:
<?php
$url='"http://www.zzsky.cn';
$timeout=10;//等待10秒
$old_timeout=ini_get('default_socket_timeout');
ini_set('default_socket_timeout',$timeout);
$contents=file_get_contents($url);
ini_set('default_socket_timeout',$old_timeout);
?>
第二種方法:
<?php
$url='"http://www.zzsky.cn';
$ctx=stream_context_create(array(
'http'=>array(
'timeout'=>10//等待10秒
)
)
);
return file_get_contents($url,0,$ctx);
?>