How can one ensure that HTTP requests are successful when fetching data from external sources in PHP, such as in the provided code snippet?
To ensure that HTTP requests are successful when fetching data from external sources in PHP, one should check the response status code to verify if the request was successful. This can be done by using the `curl_getinfo()` function to retrieve the HTTP response code. If the response code is in the 200 range, then the request was successful. If the response code is not in the 200 range, then there was an error and appropriate action can be taken.
$url = 'https://api.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 >= 200 && $httpCode < 300) {
// Request was successful, process the data
echo $response;
} else {
// Request failed, handle the error
echo 'Error: HTTP request failed with status code ' . $httpCode;
}
curl_close($ch);