What steps can be taken to troubleshoot and resolve the error message "failed to open stream: HTTP request failed! HTTP/1.1 401 Unauthorized" in PHP?

The error message "failed to open stream: HTTP request failed! HTTP/1.1 401 Unauthorized" typically indicates that the server is returning a 401 Unauthorized status code when trying to access a resource. To resolve this issue, you may need to provide proper authentication credentials (such as a username and password) in your HTTP request headers.

<?php
$url = 'http://example.com/api/resource';
$username = 'your_username';
$password = 'your_password';

$context = stream_context_create([
    'http' => [
        'header' => "Authorization: Basic " . base64_encode("$username:$password")
    ]
]);

$response = file_get_contents($url, false, $context);

if ($response === false) {
    die('Error accessing the resource.');
}

echo $response;
?>