Last month, Lorna Jane Mitchell posted an article titled “Consuming REST with PHP and Streams“. In the article, Ms. Mitchell demonstrates a clever way to use RESTful services from PHP, making use of streams. This is arguably a better alternative to the standard approach of using PHP’s cURL extension. It’s a clever solution, and not one I’d come across before.
Ever since PHP 4.3, it’s been possible to create a “stream context” using the stream_context_create() function. The “stream context” let’s you customize stream interactions, by doing such things as setting the HTTP method to be used (GET, POST, etc.), add additional headers, pass along data, and so forth. Once you’ve created a stream context, you can provide the context to functions like file_get_contents() to customize how the function behaves. Basically, anything you might do to customize a cURL request can also be done via stream contexts.
There are three obvious benefits to this approach. First, it does not require that the cURL extension be installed. Second, it doesn’t require that you use cURL! And, third, it allows you to take advantage of other stream benefits, like the ability to handle responses in chunks. (For large requests, in terms of the data in either direction, that can be a significant benefit.)