OAuth2 with PHP’s built in Streams Functions
(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:
// assemble the options $opts = array( 'http'=>array( 'header'=> "Authorization: Bearer " . $access_token ) ); // create the context $context = stream_context_create($opts); // now make the request! Use the context and simply output the result echo file_get_contents('http://api.example.com/endpoint1', false, $context);
If you’re trying to make an API call from PHP and installing better tools is hard for any reason, this example may help!
Great, it always good to be reminded that you don’t always need an heavyweight library for simple HTTP requests. But note that you probably want to use an HTTPS endpoint with proper security (see http://www.docnet.nu/tech-portal/2014/06/26/ssl-and-php-streams-part-1-you-are-doing-it-wrongtm/C0 for details) when sending an OAuth authorization token. Even if it just an example, security should not be left out.
Pingback: PHP Annotated Monthly – January 2016 | PhpStorm Blog