给file_get_contents函数设置超时时间

java哥 阅读:866 2021-02-10 11:25:00 评论:0
$opts = array( 
'http'=>array( 
'method'=>"GET", 
'timeout'=>60, 
) 
); 
 
$context = stream_context_create($opts); 
 
$html =file_get_contents('http://www.example.com', false, $context);

 

这样,file_get_contents获取数据时,超出60秒将会自动退出.

还可以利用file_get_contents函数实现post功能

function Post($url, $post = null) 
{ 
$context = array(); 
 
if (is_array($post)) { 
ksort($post); 
 
$context['http'] = array ( 
'timeout'=>60, 
'method' => 'POST', 
'content' => http_build_query($post, '', '&'), 
); 
} 
 
return file_get_contents($url, false, stream_context_create($context)); 
} 
 
$data = array ( 
'name' => 'test', 
'email' => 'test@gmail.com', 
'submit' => 'submit', 
); 
 
echo Post('http://www.example.com', $data);

 

标签:PHP
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号