What are some best practices for handling timeouts when using cURL_exec() in PHP, and how can the set_time_limit() function be utilized effectively?
When using cURL_exec() in PHP, it's important to handle timeouts effectively to prevent long waiting times. One way to do this is by setting a timeout value using the CURLOPT_TIMEOUT option in the cURL request. Additionally, you can utilize the set_time_limit() function in PHP to limit the maximum execution time of the script.
// Set a timeout value for cURL request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://example.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10); // 10 seconds timeout
$response = curl_exec($ch);
if(curl_errno($ch)){
echo 'Curl error: ' . curl_error($ch);
}
curl_close($ch);
// Limit the maximum execution time of the script
set_time_limit(30); // 30 seconds maximum execution time