Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cURL Checking for Timeout

Tags:

php

curl

timeout

I know how to set the timeout in cURL but I want to alert the user that the request timed out.

I have created an ajax script that allows the user to request data from various insurance sites and aggregate into a list. If any of the insurance sites fail to respond within a certain time I want to alert the user that the current quote from that company is not available at the moment.

Does cURL return anything to signal a timeout?

like image 699
Jack Harvin Avatar asked Feb 15 '11 12:02

Jack Harvin


People also ask

How do I check my curl timeout?

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.

How do I fix curl timeout error?

Try to increase your Server Memory Limits settings; Ask your host if there is some limitation with wp-cron, or if loopback is disabled; Ask your host if there a firewall, CDN, or security modules (e.g. mod_security) that could block the outgoing cURL requests.

How do I specify timeout in curl?

To set a timeout for a Curl command, you can use the --connect-timeout parameter to set the maximum time in seconds that you allow Curl to connect to the server, or the --max-time (or -m) parameter for the total time in seconds that you authorize the whole operation.

What causes a curl timeout?

There are many reasons for curl not working. Some of them can be, 1) Response time is slow. 2) Few site has check on few header parameters to respond to request. These parameters include User-Agent, Referer, etc to make sure it is coming from valid source and not through bots.


2 Answers

curl_errno() returns 28 if the operation timed out. See http://curl.haxx.se/libcurl/c/libcurl-errors.html for other error codes.

like image 168
rik Avatar answered Oct 01 '22 15:10

rik


Or another solution that can cover even more cases (server timed out, server errored out with a blank page) is to check if your get_url function result is different that "" or FALSE.

Example of get_url function :

function get_url($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    $tmp = curl_exec($ch);
    curl_close($ch);
    return $tmp;
}
like image 38
Sorin Trimbitas Avatar answered Oct 01 '22 14:10

Sorin Trimbitas