What are some best practices for troubleshooting cURL errors in PHP scripts?

When troubleshooting cURL errors in PHP scripts, it is important to check for common issues such as incorrect URLs, SSL certificate problems, or server timeouts. One best practice is to enable verbose mode in cURL to get more detailed error messages. Additionally, checking the response code and error messages can help pinpoint the issue.

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

// Set the URL to fetch
curl_setopt($ch, CURLOPT_URL, 'https://example.com');

// Enable verbose mode to get detailed error messages
curl_setopt($ch, CURLOPT_VERBOSE, true);

// Execute the cURL session
$response = curl_exec($ch);

// Check for errors
if($response === false) {
    echo 'cURL error: ' . curl_error($ch);
}

// Close cURL session
curl_close($ch);