Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cURL timeout, can you handle it elegantly?

cURL makes PHP throw a Fatal Error if it takes more than 30 seconds to get a response from the server. This seems to be happening a lot in my web app, particularly if the other server is busy. It really isn't pretty for the user to see that.

I would like to either catch the timeout and display a nice messsage myself, or alternatively, I was wondering if there was a way I could continue with the rest of the PHP script, as the rest of that script can execute even if there is no response from the server (with default values).

I don't really see why cURL would throw a Fatal Error instead of a Warning for the timeout to be honest. It's a real pain.

like image 351
Juicy Avatar asked Oct 09 '13 17:10

Juicy


People also ask

How long does it take for curls to time out?

The default is 60 seconds.

What causes a curl timeout?

Several factors could cause this, including a slow network connection, network congestion, or a low connection timeout limit on the server.

How do you pass timeout in curl command?

Tell curl with -m / --max-time the maximum time, in seconds, that you allow the command line to spend before curl exits with a timeout error code (28). When the set time has elapsed, curl will exit no matter what is going on at that moment—including if it is transferring data. It really is the maximum time allowed.


2 Answers

This is a slightly more literal answer to the question. That is, curl will still stop after 30 seconds, but you can catch the error and keep going if you want.

ini_set('max_execution_time', 40); // prevents 30 seconds from being fatal

$ch = curl_init();

curl_setopt($ch, CURLOPT_TIMEOUT, 30); // curl timeout remains at 30 seconds
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_exec($ch);

if ($error_number = curl_errno($ch)) {
    if (in_array($error_number, array(CURLE_OPERATION_TIMEDOUT, CURLE_OPERATION_TIMEOUTED))) {
        print "curl timed out";
    }
}

curl_close($ch);

If you have no control over the max_execution_time, you can just lower the curl timeout slightly.

like image 158
cesoid Avatar answered Oct 30 '22 15:10

cesoid


Increase the cURL timeout using these params

curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0); 
curl_setopt($ch, CURLOPT_TIMEOUT, 500);

Since you mentioned 30 seconds, i suspect that your PHP Script timeout is running out. So add this to your PHP code.

set_time_limit(0);// 0 is infite limit 
like image 44
Shankar Narayana Damodaran Avatar answered Oct 30 '22 15:10

Shankar Narayana Damodaran