How can HTTP response codes be utilized to troubleshoot issues with Curl and file_get_contents in PHP?

When using Curl or file_get_contents in PHP to make HTTP requests, it is important to check the HTTP response codes to troubleshoot any issues that may arise. By checking the response codes, you can determine if the request was successful, unauthorized, or encountered an error. This information can help you identify and resolve any problems with the request.

$url = 'https://example.com/api';
$response = file_get_contents($url);
$httpCode = substr($http_response_header[0], 9, 3);

if ($httpCode == 200) {
    // Request was successful
    echo $response;
} else {
    // Handle errors based on response code
    echo 'Error: ' . $httpCode;
}