Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

OAuth2 With PHP's Built-in Streams Functions

DZone's Guide to

OAuth2 With PHP's Built-in Streams Functions

If you're working with APIs from PHP, Guzzle might be useful considering how easy to use it is, and up to date. Check out this look at OAuth2 with PHP's built-in stream functions in this great snippet.

· Performance Zone
Free Resource

Discover 50 of the latest mobile performance statistics with the Ultimate Guide to Digital Experience Monitoring, brought to you in partnership with Catchpoint.

Most of the time when I work with APIs from PHP, I use Guzzle - it's awesome, modern, and elegant. However some of my work is with legacy platforms and I recently had a situation where we needed to integrate with an 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:


// 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!

Is your APM strategy broken? This ebook explores the latest in Gartner research to help you learn how to close the end-user experience gap in APM, brought to you in partnership with Catchpoint.

Topics:
php

Published at DZone with permission of Lorna Mitchell, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}