file_get_contents函数使用注意

PHP 程序员们喜欢使用简单便捷的 file_get_contents("http://example.com/") 函数,来获取一个 URL 的返回内容,但是,如果 <a href="http://example.com/" target="_blank">http://example.com</a> 这个网站响应缓慢,file_get_contents() 就会一直卡在那儿,不会超时。


解决办法:

<?php

$ctx = stream_context_create(array(

‘http’ => array(
‘timeout’ => 1 //设置一个超时时间,单位为秒
)
)

);

file_get_contents("http://example.com/", 0, $ctx);

?>