What are the best practices for handling HTTP error codes, such as 403 Forbidden, when retrieving data from URLs in PHP?

When retrieving data from URLs in PHP, it is important to handle HTTP error codes properly to ensure the application can gracefully respond to issues like 403 Forbidden. One common approach is to check the HTTP response code before processing the data, and take appropriate action based on the code received.

$url = 'https://example.com/data';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if ($httpCode == 403) {
    // Handle 403 Forbidden error
    echo '403 Forbidden - Access Denied';
} elseif ($httpCode == 200) {
    // Process the data
    $data = json_decode($response, true);
    // Do something with the data
} else {
    // Handle other HTTP error codes
    echo 'HTTP Error ' . $httpCode;
}

curl_close($ch);