OAuth2 with PHP’s built in Streams Functions

Most of the time when I work with APIs from PHP, I use Guzzle – it’s awesome and modern and elegant. However some of my work is with legacy platforms and I recently had a situation where we needed to integrate with a API using OAuth2, and launch that integration before the planned platform upgrade from an older version of PHP was expected to complete.

(this drives me nuts, I love upgrading systems but the downside is you have to work with the old ones first and none of the tools you want have been invented yet!)

For OAuth2, all I had to be able to do was to send an Authorization header with my web request from PHP. My second-favourite way of making API calls from PHP is to use PHP’s stream handling, so I did that. It’s not code you see very often but it’s super-simple and it works on every PHP platform I’ve tried so far, so here’s an example:

$vcap_services = json_decode($_ENV['VCAP_SERVICES'], true);
$uri = $vcap_services['compose-for-mysql'][0]['credentials']['uri'];
$db_creds = parse_url($uri);
$dbname = "your_database_name";

$dsn = "mysql:host=" . $db_creds['host'] . ";port=" . $db_creds['port'] . ";dbname=" . $dbname;
$db = new PDO($dsn, $db_creds['user'], $db_creds['pass']);

If you’re trying to make an API call from PHP and installing better tools is hard for any reason, this example may help!

2 thoughts on “OAuth2 with PHP’s built in Streams Functions

  1. Pingback: PHP Annotated Monthly – January 2016 | PhpStorm Blog

Leave a Reply

Please use [code] and [/code] around any source code you wish to share.

This site uses Akismet to reduce spam. Learn how your comment data is processed.