What are some best practices for setting timeouts in cURL requests to avoid script timeouts in PHP?
When making cURL requests in PHP, it's important to set timeouts to prevent the script from hanging indefinitely if the remote server is slow or unresponsive. By setting both a connection timeout and a maximum execution time for the request, you can ensure that your script doesn't run longer than intended. This can help prevent script timeouts and improve the overall performance of your application.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://example.com/api');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); // set connection timeout to 5 seconds
curl_setopt($ch, CURLOPT_TIMEOUT, 10); // set maximum execution time to 10 seconds
$response = curl_exec($ch);
curl_close($ch);
if ($response === false) {
// handle timeout or connection error
} else {
// process the response
}