Setting an authorization header when using file_get_contents with PHP

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
file_get_contents() method.

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
file_get_contents().

This should work similarly with a other authorization types, like Bearer, but
for this post, we’ll be using a Basic authorization.

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: username:password.

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!

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.