Going through some of my old lists of blog post ideas this weekend. While it’s
not something I’ve needed for a minute, it’s still something worth taking about.
How to set an authorization header when using PHP’s wonderful
Similar to an old post of mine talking about specifying a User Agent,
we’ll be working with a “stream context” that will be passed to
This should work similarly with a other authorization types, like
for this post, we’ll be using a
Something to note, when passing in a
Basic header, you’ll want to encode the
user name and password combination in
base64 format. The format of the user
name and password will be colon delimited like this:
To create the stream context, we’ll need to pass in an array that tells it that we’d like to set an HTTP header, and include the relevant authorization information:
$credentials = base64_encode('username:password'); $options = ['http' => ['header' => "Authorization: Basic $credentials"]]; $context = stream_context_create($options); $response = file_get_contents('http://domain/path/to/uri', false, $context);
Not much to it, and if need be, you can combine additional headers as part of the options!