如何在php中限制http响应时间

Gir*_*iri 4 php function http-headers

我正在使用一些网站来检测我的网站访问者的国家/地区.我的意思是这样的

$ip = $_SERVER['REMOTE_ADDR'];  
$url1 = 'http://api.hostip.info/get_json.php?ip='.$ip;
$url2 = 'http://ip2country.sourceforge.net/ip2c.php?format=JSON&ip='.$ip;
Run Code Online (Sandbox Code Playgroud)

有时像sourgeforge这样的网站需要花费太多时间来加载.

所以任何人都可以告诉如何限制http响应时间.

如果url1是关闭或没有回应x seconds然后转移到url2,url3,etc

goa*_*oat 5

$context  = stream_context_create(array(
    'http' => array(
        'method'  => 'GET',
      , 'timeout' => 3 
    )
));
Run Code Online (Sandbox Code Playgroud)

然后将流上下文提供给fopen()或file_get_contents()等...

http://php.net/manual/en/stream.contexts.php
http://php.net/manual/en/context.http.php

手册称为"读取超时".我担心它可能不包括像dns解析+套接字连接之类的东西.我认为php尝试从流中读取之前的超时可能受default_socket_timeout设置的控制.

你可能想要考虑卷曲,它看起来有点具体,但我不确定是否CURLOPT_TIMEOUT包含CURLOPT_CONNECTTIMEOUT.

$ch = curl_init();
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($ch, CURLOPT_TIMEOUT, 2);
Run Code Online (Sandbox Code Playgroud)

http://php.net/manual/en/function.curl-setopt.php