CURL timeout, can you handle it gracefully?

cURL causes PHP to cause a fatal error if it takes more than 30 seconds to get a response from the server. This seems to be happening in my web application, especially if another server is busy. It really is not very pleasant for the user.

I would either catch a timeout, or show a nice messsage myself, or, conversely, I was wondering if there is a way to continue working with the rest of the PHP script, since the rest of this script can be executed even if there is no response from the server ( with default values).

I really don't understand why cURL chose Fatal Error instead of a warning for a timeout, to be honest. This is a real pain.

+8
php curl fatal-error
source share
2 answers

Increase cURL timeout with these options

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

Since you specified 30 seconds, I suspect that the PHP Script timeout is not working. So add this to your PHP code.

 set_time_limit(0);// 0 is infite limit 
+5
source share

This is a slightly more literal answer to the question. That is, the 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 do not have control over max_execution_time, you can slightly reduce the waiting time for curls.

+4
source share

All Articles