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.
The default is 60 seconds.
Several factors could cause this, including a slow network connection, network congestion, or a low connection timeout limit on the server.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With