To communicate with APIs or web services over HTTP, an HTTP client such as cURL is required. Thankfully, PHP can be bundled with cURL.

Most people new to PHP and programming in general and even the experienced ones find cURL daunting and complex as a result, some expert developers have developed libraries that takes the pain out of consuming web services using cURL such as Guzzle.

In this article, we will take a look at yet another PHP HTTP Client called Unirest for PHP powered under-the-hood by cURL.

Unirest generally is a lightweight HTTP request client libraries created by the Mashape team available in seven different languages: PHP, Python, Ruby, Nodejs, .NET, Objective-C and Java. Our focus is on that of PHP. GitHub repository here.

Installation

Unirest for PHP can be installed via composer or cloning the GitHub repository.

To install via composer, add the following to your composer.json file.

{ "require" : { "mashape/unirest-php" : "dev-master" }, "autoload": { "psr-0": {"Unirest": "lib/"} } }

Run composer install to download the library.

Clone the PHP library from Github to your project use the command below:

Note Unirest-PHP requires PHP v5.3+

Next, include it in to your script:

require_once '/path/to/unirest-php/lib/Unirest.php';

If installation was done via composer, include the vendor/autoload.php autoloader file.

require_once 'vendor/autoload.php';

Getting Started with Unirest for PHP

Unirest for PHP supports the following HTTP verbs or requests: GET, POST, PUT, PATCH and DELETE.

Below is the function synopsis for sending the above requests via Unirest for PHP HTTP client.

Unirest::get($url, $headers = array(), $parameters = NULL, $username = NULL, $password = NULL) Unirest::post($url, $headers = array(), $body = NULL, $username = NULL, $password = NULL) Unirest::put($url, $headers = array(), $body = NULL, $username = NULL, $password = NULL) Unirest::patch($url, $headers = array(), $body = NULL, $username = NULL, $password = NULL) Unirest::delete($url, $headers = array(), $body = NULL, $username = NULL, $password = NULL)

Where:

$url – Endpoint or url to be acted upon.

$headers – The request header as associative array or object.

$body – Request Body as associative array or object.

$username – Basic Authentication username.

$password – Basic Authentication password.

Upon receiving a response, Unirest returns the result in Object form broken into four properties:

code – HTTP Response Status Code.

headers – HTTP Response Headers

body – Response body parsed to an Objects / Associative Arrays.

raw_body – Un-parsed response body.

Making HTTP GET Request

While in search of an API for use as an example in this tutorial, I stumbled on JsonWhois, a whois, social data & stats API service.

Let’s see how Unirest for PHP consumes an API or web service.

"application/json" ), array( "apiKey" => "54183ad8c433fac10b6f5d7c", "domain" => "sitepoint.com" ) );

Code explanation: In the first line, the Unirest library gets included.

A GET request to the url http://jsonwhois.com/api/whois is created using the Unirest get method.

The second method argument – request headers – tell the server what content types the HTTP client will accept.

Finally, the third method argument is the request parameters.

As previously stated, the parsed response body is located in body property.

$response->body

Making HTTP POST Requests

Say you’ve implemented reCAPTCHA in your website sign-up form.

To verify if the user passed or failed the captcha test, a POST request to http://www.google.com/recaptcha/api/verify is created together with the following parameters or request body:

– privatekey : Your private key.

– remoteip : The IP address of the user who solved the CAPTCHA.

– challenge : The value of “recaptcha_challenge_field” sent by the form.

– response : The value of “recaptcha_response_field” sent via the form.

$private_key, 'remoteip' => $_SERVER["REMOTE_ADDR"], 'challenge' => $_POST['recaptcha_challenge_field'], 'response' => $_POST['recaptcha_response_field'] ) ); print_r($response->body);

If the captcha test was passed, the reCAPTCHA API returns:

true success

Otherwise the following error is returned

false incorrect-captcha-sol

To get your captcha verification function or method to return a Boolean value i.e. true on success and false on failure; explode the API response and trim the array data with index 0 .

$response_body = explode( "n", $response->body ); $response_body = trim( $response_body[0] ); return $response_body;

Other supported request types setup – PUT, PATCH, DELETE are synonymous to the above examples.

Features / Settings worth Noting

File Uploads

To upload files in a multipart form representation, use the return value of Unirest::file('path/to/file.txt') as the value of a parameter or request body.

$response = Unirest::post("http://httpbin.org/post", array( "Accept" => "application/json" ), array( "file" => Unirest::file("https://w3guy.com/folder/file.txt") ) );

Custom Entity Body

Sending a custom body such as a JSON Object rather than a string or form style parameters is possible with Unirest.

$json_data = json_encode( array( "parameter" => "value", "foo" => "bar" ) ); $response = Unirest::post( "http://httpbin.org/post", array( "Accept" => "application/json" ), $json_data );

Basic Authentication

Authenticating the request with basic authentication can be done by providing the username and password arguments:

$response = Unirest::get("http://httpbin.org/get", null, null, "username", "password");

Timeout

A custom timeout value (in seconds) can be set as follows:

Unirest::timeout(5); // 5s timeout

SSL validation

You can explicitly enable or disable SSL certificate validation when consuming an SSL protected endpoint/url.

By default, this is set as true (enabled).

Unirest::verifyPeer(false); // Disables SSL cert validation

Other Light-weight PHP HTTP Clients

I stumbled on two other light-weight HTTP clients for PHP during my research and deem it necessary to share them with us.

1. Httpful: a simple, chain-able, readable PHP library intended to make speaking HTTP sane.

2. Buzz: a lightweight PHP 5.3 library for issuing HTTP requests.

Summary

Thus far, we’ve seen the features of **Unirest for PHP** and how to make HTTP request with it.

Aside Unirest and the other light-weight HTTP client mentioned, what HTTP client are you using for your project or have experience working with? We’ll love to hear them in the comments.