Specifying a User Agent when using file_get_contents() in PHP

Josh Sherman
1 min read
Software Development PHP

I recently encountered a scenario where one of my site’s login system stopped working. The piece of code that stopped working was the third-party login that leveraged GitHub for the authentication. It was one of those “it worked yesterday” moments for sure.

After some research, I discovered that GitHub had changed their API to make it mandatory to specify the user agent header for all of it’s API calls. This was all well and good and I hopped in to make the change only to realize that the code that was failing was using file_get_contents() and well, it worked fine for a quick GET of the URL in the past but I had never used it in conjunction of HTTP headers, that’s typically where I’d use cURL.

I didn’t necessary want to rewrite the code to use cURL so I went ahead and consulted the PHP documentation for file_get_contents() only to discover that you can pass in a custom stream context to set the header’s you’d like to be passed along. It adds a few more lines of code (it could easily be done in one long line if so inclined) and got the job done in resolving my issue.

$options  = array('http' => array('user_agent' => 'custom user agent string'));
$context  = stream_context_create($options);
$response = file_get_contents('http://domain/path/to/uri', false, $context);

So that got everything up and running again but it begged the question, what about error handling? As it turns out file_get_contents() simply returns false when it fails. That by itself can prove problematic if you forget to use check for equality (===) but by design the function lacks error reporting. Although using the context fixed the issue I will still be going back and rewriting the code to use cURL so that I can have better error handling in the future thanks to curl_errno() and curl_error().

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, Engineering Manager 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