cURL timeout, can you handle it elegantly?

Juicy picture Juicy · Oct 9, 2013 · Viewed 12.7k times · Source

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.

Answer

cesoid picture cesoid · Jan 14, 2016

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.