当前位置: 移动技术网 > IT编程>开发语言>PHP > PHP请求远程地址设置超时时间的解决方法

PHP请求远程地址设置超时时间的解决方法

2017年12月12日  | 移动技术网IT编程  | 我要评论

php请求远程地址设置超时时间,主要讲解file_get_contents、fopen、curl这三个简单常用函数设置超时时间的方法,一般情况下建议使用curl,性能最好,效率也最高。

1、file_get_contents 请求超时设置

$timeout = array(
'http'=> array(
'timeout'=>5//设置一个超时时间,单位为秒
)
);
$ctx = stream_context_create($timeout);
$text = file_get_contents("//www.jb51.net/",0, $ctx);

2、fopen 请求超时设置

$timeout = array(
'http' => array(
'timeout' => 5 //设置一个超时时间,单位为秒
)
);
$ctx = stream_context_create($timeout);
if ($fp = fopen("//www.jb51.net/", "r", false, $ctx)) {
while( $c = fread($fp, 8192)) {
echo $c;
}
fclose($fp);
}

3、curl请求超时设置

curl 是常用的访问http协议接口的lib库,性能高,还有一些并发支持的功能等。

curl_setopt($ch, opt) 可以设置一些超时的设置,主要包括:

a 、curlopt_timeout 设置curl允许执行的最长秒数。

b、curlopt_timeout_ms 设置curl允许执行的最长毫秒数。

c、 curlopt_connecttimeout 在发起连接前等待的时间,如果设置为0,则无限等待。

d、 curlopt_connecttimeout_ms 尝试连接等待的时间,以毫秒为单位。如果设置为0,则无限等待。e、 curlopt_dns_cache_timeout 设置在内存中保存dns信息的时间,默认为120秒。

$ch = curl_init();
curl_setopt($ch, curlopt_url,$url);
curl_setopt($ch, curlopt_returntransfer,1);
curl_setopt($ch, curlopt_timeout,60);  //只需要设置一个秒的数量就可以
curl_setopt($ch, curlopt_httpheader, $headers);
curl_setopt($ch, curlopt_useragent, $defined_vars['http_user_agent']);

以上就是小编为大家带来的php请求远程地址设置超时时间的解决方法全部内容了,希望大家多多支持移动技术网~

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网