What are the best practices for handling HTTP status codes when using cURL in PHP?
When making HTTP requests using cURL in PHP, it is important to handle HTTP status codes properly to ensure that the request was successful or to handle any errors that may have occurred. This can be done by checking the HTTP status code returned by the server in the response headers. By examining the status code, you can determine if the request was successful (status code 200) or if there was an error (status codes like 400 or 500).
<?php
// 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 session
$response = curl_exec($ch);
// Get the HTTP status code
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Check the HTTP status code
if ($http_status == 200) {
// Request was successful, process the response
echo "Request was successful!";
} else {
// Handle the error based on the HTTP status code
echo "Error: HTTP status code " . $http_status;
}
// Close cURL session
curl_close($ch);
?>