file_get_content没远程没响应解决方案

 

file_get_contents是个好东西,在接口调用中经常用到,弊端就是在远程接口没有响应时,执行就会卡住直到超时很不爽,于是修改http头,如下:
 
$ctx=stream_context_create(array(
        'http'=>array(
            'timeout'=>3//等待3秒
            )
        )
    );
    $result = @file_get_contents ( $url,0,$ctx );
 
bingo,解决问题,另一种思路是模拟请求:
 
function file_get_content($url) {
        $ch = curl_init();   
        $timeout = 3;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $result = curl_exec($ch);
        curl_close($ch);
}
 




原文地址:https://www.cnblogs.com/firmy/p/2818975.html