Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit http response time in php

I'm using some sites to detect my site visitor's country. I mean like this

$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;

Sometimes sites like sourgeforge taking too much time to load.

So can anyone tell how to limit the http response time.?

if url1 is down or not responded in x seconds then move to url2,url3,etc

like image 215
Giri Avatar asked Feb 18 '23 01:02

Giri


1 Answers

$context  = stream_context_create(array(
    'http' => array(
        'method'  => 'GET',
      , 'timeout' => 3 
    )
));

Then supply the stream context to fopen() or file_get_contents() etc...

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

The manual calls that a "read timeout". I worry it may not include time for stuff like dns resolution + socket connection. I think the timeout before php tries reading from the stream may be governed by the default_socket_timeout setting.

You may want to consider curl, it seems a bit more specific, but I'm not sure if CURLOPT_TIMEOUT is inclusive of CURLOPT_CONNECTTIMEOUT.

$ch = curl_init();
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($ch, CURLOPT_TIMEOUT, 2);

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

like image 107
goat Avatar answered Feb 28 '23 07:02

goat