What are best practices for error handling in cURL requests within PHP scripts?

When making cURL requests within PHP scripts, it is important to implement proper error handling to catch any potential issues that may arise during the request. This can include checking for errors, timeouts, or other connection problems. One common approach is to use the curl_errno() and curl_error() functions to check for errors and handle them accordingly.

// Initialize cURL session
$ch = curl_init();

// Set cURL options
curl_setopt($ch, CURLOPT_URL, 'https://api.example.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute cURL request
$response = curl_exec($ch);

// Check for cURL errors
if(curl_errno($ch)) {
    echo 'cURL error: ' . curl_error($ch);
    // Handle the error accordingly, such as logging it or displaying a message
} else {
    // Process the response data
    echo $response;
}

// Close cURL session
curl_close($ch);