Derekthar
Derekthar

Reputation: 543

Control timeout for a CURL call doesn't work

I need to make a call to an external service using CURL, the problem is that sometimes it takes a long response time, and my page is suspended until it receives response.

I used the CURLOPT_CONNECTTIMEOUT and CURLOPT_TIMEOUT options but has no effect. I read that CURL, also makes use of the "default_socket_timeout" variable, but still the request always takes 55 seconds before being canceled.

It seems like CURL ignore any option or configuration.

ini_set("max_execution_time", 10);
ini_set("default_socket_timeout", 10);
set_time_limit(5);

$start = time();

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://localhost/test/sleep.php');

curl_setopt($curl, CURLOPT_USERAGENT, $headers);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_MAXREDIRS, 5);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLINFO_HEADER_OUT, true);
curl_setopt($curl, CURLOPT_HEADER, false);

curl_setopt($curl, CURLOPT_FRESH_CONNECT, 1);
curl_setopt($curl, CURLOPT_NOSIGNAL, 1);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 3);
curl_setopt($curl, CURLOPT_TIMEOUT, 8);

curl_exec($curl);

$end = time() - $start;
echo '>>>'.$end.'<<<';

Output:

>>>55<<

Note: sleep.php only have an infinite loop. And I see that in the server: max_execution_time was 60 and default_socket_timeout was 30 before I changed it to 10 seconds.

Upvotes: 2

Views: 2832

Answers (1)

Sepultura
Sepultura

Reputation: 1047

your configuration is correct and works as expected. the problem is that curl IS able to connect to your script (sleep.php) so the connection timeout isn't triggered. The 55 seconds are probably from the max_execution_time.

try to connect to a random ip-address instead of localhost and you will see that the connection-timeout is working.

edit: also the CURLOPT_TIMEOUT is working, I have testet it with an script which contains an infinit loop and the curl-request gets stopped after 8 sec.

Upvotes: 1

Related Questions