Blog

pecl_http 2.x example

Previously, I was using pecl_http 1.7.6 and life was easy – all I was using (and needed) was the http_get() API.  However, v2 of the API was completely overhauled.  Gone are the static, c-style APIs, instead replaced with a full object-oriented API.  One could argue that this change was long overdue, but it was a jarring change – the old APIs weren’t simply deprecated, they were removed.

As with any new API, I wanted to see an example.  After all, replacing http_get() with object-oriented counterpart should be trivial, right?  So I set out to find a good, simple pecl_http 2.x example.  The docs are a good place to start, but honestly didn’t scratch my itch.  Frankly I could care less about the specifics – please just give me some PHP that I can run with.  And I’m not the only one – more than a few people have complained about the lack of examples.

That said, here’s my implementation of http_get(), using the new 2.x constructs:

<?php
// NOTE: CORS access is set to all (*), to allow for easy access from a Web client (AJAX).
// Under normal circumstances you would not want to do this, or at least restrict to well-known hosts.
header("Access-Control-Allow-Origin: *");

if (!isset($_GET["url"])) {
echo "missing required input: url.";
http_response_code(400);
exit();
}

$url = $_GET["url"];
if (strlen($url) == 0) {
echo "url cannot be empty.";
http_response_code(400);
exit();
}

$req = new \http\Client\Request("GET", $_GET["url"]);

try {
$client = (new \http\Client())
->enqueue($req)
->send();

$resp = $client->getResponse();
echo "HTTP/" . $resp->getHttpVersion() . " " . $resp->getResponseCode() . " " . $resp->getResponseStatus() . "\n";

foreach($resp->getHeaders() as $key => $value) {
echo $key . ": " . $value . "\n";
}

echo "\n" . $resp->getBody();
} catch (Exception $e) {
echo $e->getMessage();
echo $e->getCode();
echo $e->getTraceAsString();
http_response_code(500);
}
?>

This snippet with issue an HTTP GET to the specified URL and print out the status code/text, all response headers and the full body of the request. Includes very minimal validation and error handling, as this is used for development purposes. This is how the old http_get() API functions. Likewise the Access-Control-Allow-Origin response header is set to ‘*’ to allow for easy access via AJAX, but not advised for general use.


NOTE: try-catch is only available in PHP 5+. The http_response_code API is only available in PHP 5.4+, otherwise you’ll have to use the existing header() API.

Leave Reply