How can PHP developers handle errors effectively when using cURL for HTTP requests?
When using cURL for HTTP requests in PHP, developers can handle errors effectively by checking the response code and error message returned by cURL. By using the curl_error() and curl_errno() functions, developers can determine if an error occurred during the request and take appropriate action, such as logging the error or retrying the request.
// 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 errors
if($response === false) {
$error_message = curl_error($ch);
$error_code = curl_errno($ch);
// Handle the error accordingly
echo "cURL error: $error_message (Error code: $error_code)";
}
// Close cURL session
curl_close($ch);