Subscribe to PHP Freaks RSS

PHP: file_get_contents with basic auth and redirects

syndicated from planet-php.net on September 20, 2020

I used PHP's file_get_contents() to fetch the content of an URL:

$content = file_get_contents('https://username:password@example.org/path');

This worked fine until that URL redirected to a different path on the same domain. An error was thrown then:

PHP Warning: file_get_contents(http://...@example.org): failed to open stream: HTTP request failed! HTTP/1.1 401 Unauthorized

The solution is to use a stream context and configure the HTTP basic auth parameters into it. Those parameters are used for redirects, too.

$user = 'user';
$pass = 'pass';
$opts = [
    'http' => [
        'method' => 'GET',
        'header' => 'Authorization: Basic ' . base64_encode($user . ':' . $pass)
    ]
];
file_get_contents($baUrl, false, stream_context_create($opts));