Setting an authorization header when using file_get_contents with PHP

Josh Sherman
1 min read
Software Development 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!

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

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.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles