fwrite($fp,"Connection: Close\r\n\r\n");
stream_set_blocking($fp,true); //重要,设置为非阻塞模式
stream_set_timeout($fp,$timeout); //设置超时
$info = stream_get_meta_data($fp);
while((!feof($fp))&&(!$info['timed_out'])){
$data .= fgets($fp,4096);
$info = stream_get_meta_data($fp);
ob_flush;
flush();
}
if($info['timed_out']){
echo "Connection Timed Out!";
}else{
echo $data;
}}
file_get_contents 超时:
<?php
$timeout = array(
'http'=> array(
'timeout'=>5//设置一个超时时间,单位为秒
)
);
$ctx = stream_context_create($timeout);
$text = file_get_contents("http://example.com/",0, $ctx);
fopen 超时:
<?php
$timeout = array(
'http' => array(
'timeout' => 5 //设置一个超时时间,单位为秒
)
);
$ctx = stream_context_create($timeout);
if ($fp = fopen("http://example.com/", "r", false, $ctx)) {
while( $c = fread($fp, 8192)) {
echo $c;
}
fclose($fp);
}