William L.
William L.

Reputation: 3886

Retry curl request if it times out in php?

Is there a way to retry a curl request in php after it fails, I want it to retry about 5 times if it times out but I'm not sure how to do this. Should I use curl_errno($ch) to check if it's a time-out then run a whole new curl request, or is there an easier way to do it?

Upvotes: 2

Views: 7400

Answers (1)

Marcus Hughes
Marcus Hughes

Reputation: 5493

cURL has pre-defined error codes, you can find them here: http://curl.haxx.se/libcurl/c/libcurl-errors.html The one we're after is 28, for CURLE_OPERATION_TIMEDOUT. It should be returned numerically on curl_errno, so we can use the 28 comparison to check for timeouts.

I'd suggest you loop through until you don't get the 28, you can do this with while and also add an and to reach the limit, like this

$limit  =   0;
while((curl_errno($ch) == 28 or $limit == 0) and $limit < 5){
    $limit++;
    // Run curl stuff
}

You should of course add your curl fetches in the loop too. So yes, I think you need to run the curl command again. I would also recommend placing a sleep before retrying to something like after the $limit++; line adding

if($limit > 0) sleep(1);

I am assuming this will be used on the CLI so sleeps shouldn't be a problem. You just don't want to hammer a HTTP server, you may not know its firewall rules and such

Upvotes: 4

Related Questions