I’m using cURL in PHP to fetch data from an external API. Sometimes the request times out or fails due to a temporary network issue. I want to set a timeout and also retry the request a few times before giving up.
What’s the best way to implement this in a clean and reliable way?
Should I use CURLOPT_TIMEOUT
or CURLOPT_CONNECTTIMEOUT
, or both?
Also, how can I properly loop the retries while avoiding infinite loops or bad practices?
Sample code would be really helpful!
Been a long time since i did anything with cURL in PHP, but sniffing curl_errno
should be the answer?
To handle timeouts and retries in cURL with PHP, you can use both CURLOPT_TIMEOUT and CURLOPT_CONNECTTIMEOUT to control the overall timeout and connection timeout. Here’s an example implementation that retries the request up to 3 times before giving up:
<?php
function fetch_data_with_retries($url, $max_retries = 3) {
$attempt = 0;
$timeout = 10; // seconds
$connect_timeout = 5; // seconds
while ($attempt < $max_retries) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); // Total timeout
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connect_timeout); // Connection timeout
$response = curl_exec($ch);
if ($response === false) {
$attempt++;
echo "Attempt $attempt failed. Retrying...\n";
sleep(2); // Optional: Sleep between retries
} else {
curl_close($ch);
return $response;
}
}
echo "All attempts failed.\n";
curl_close($ch);
return null; // Return null if all retries fail
}
$response = fetch_data_with_retries("https://api.example.com/data");
if ($response) {
echo "Data fetched successfully!";
} else {
echo "Failed to fetch data after retries.";
}
?>
Your AI’s doing a bit more echoing than it needed to, and should probably be echoing the actual error associated with the failure rather than generic statements.
Also, the echo’s been structured for a CLI implementation.