Unirest is a set of lightweight HTTP libraries available in multiple languages.

Overview

Unirest for PHP

version Downloads Tests License

Unirest is a set of lightweight HTTP libraries available in multiple languages.

This fork is maintained by APIMatic for its Code Generator as a Service.

Features

  • Utility methods to call GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH requests
  • Supports form parameters, file uploads and custom body entities
  • Supports gzip
  • Supports Basic, Digest, Negotiate, NTLM Authentication natively
  • Customizable timeout
  • Customizable default headers for every request (DRY)
  • Automatic JSON parsing into a native object for JSON responses

Requirements

  • PHP 5.6+
  • PHP Curl extension

Installation

To install apimatic/unirest-php with Composer, just add the following to your composer.json file:

{
    "require": {
        "apimatic/unirest-php": "^2.2.2"
    }
}

or by running the following command:

composer require apimatic/unirest-php

Usage

Creating a Request

So you're probably wondering how using Unirest makes creating requests in PHP easier, let's look at a working example:

$headers = array('Accept' => 'application/json');
$query = array('foo' => 'hello', 'bar' => 'world');

$response = Unirest\Request::post('http://mockbin.com/request', $headers, $query);

$response->code;        // HTTP Status code
$response->headers;     // Headers
$response->body;        // Parsed body
$response->raw_body;    // Unparsed body

JSON Requests (application/json)

A JSON Request can be constructed using the Unirest\Request\Body::Json helper:

$headers = array('Accept' => 'application/json');
$data = array('name' => 'ahmad', 'company' => 'mashape');

$body = Unirest\Request\Body::json($data);

$response = Unirest\Request::post('http://mockbin.com/request', $headers, $body);

Notes:

  • Content-Type headers will be automatically set to application/json
  • the data variable will be processed through json_encode with default values for arguments.
  • an error will be thrown if the JSON Extension is not available.

Form Requests (application/x-www-form-urlencoded)

A typical Form Request can be constructed using the Unirest\Request\Body::Form helper:

$headers = array('Accept' => 'application/json');
$data = array('name' => 'ahmad', 'company' => 'mashape');

$body = Unirest\Request\Body::form($data);

$response = Unirest\Request::post('http://mockbin.com/request', $headers, $body);

Notes:

  • Content-Type headers will be automatically set to application/x-www-form-urlencoded
  • the final data array will be processed through http_build_query with default values for arguments.

Multipart Requests (multipart/form-data)

A Multipart Request can be constructed using the Unirest\Request\Body::Multipart helper:

$headers = array('Accept' => 'application/json');
$data = array('name' => 'ahmad', 'company' => 'mashape');

$body = Unirest\Request\Body::multipart($data);

$response = Unirest\Request::post('http://mockbin.com/request', $headers, $body);

Notes:

  • Content-Type headers will be automatically set to multipart/form-data.
  • an auto-generated --boundary will be set.

Multipart File Upload

simply add an array of files as the second argument to to the Multipart helper:

$headers = array('Accept' => 'application/json');
$data = array('name' => 'ahmad', 'company' => 'mashape');
$files = array('bio' => '/path/to/bio.txt', 'avatar' => '/path/to/avatar.jpg');

$body = Unirest\Request\Body::multipart($data, $files);

$response = Unirest\Request::post('http://mockbin.com/request', $headers, $body);

If you wish to further customize the properties of files uploaded you can do so with the Unirest\Request\Body::File helper:

$headers = array('Accept' => 'application/json');
$body = array(
    'name' => 'ahmad', 
    'company' => 'mashape'
    'bio' => Unirest\Request\Body::file('/path/to/bio.txt', 'text/plain'),
    'avatar' => Unirest\Request\Body::file('/path/to/my_avatar.jpg', 'text/plain', 'avatar.jpg')
);

$response = Unirest\Request::post('http://mockbin.com/request', $headers, $body);

Note: we did not use the Unirest\Request\Body::multipart helper in this example, it is not needed when manually adding files.

Custom Body

Sending a custom body such rather than using the Unirest\Request\Body helpers is also possible, for example, using a serialize body string with a custom Content-Type:

$headers = array('Accept' => 'application/json', 'Content-Type' => 'application/x-php-serialized');
$body = serialize((array('foo' => 'hello', 'bar' => 'world'));

$response = Unirest\Request::post('http://mockbin.com/request', $headers, $body);

Authentication

First, if you are using Mashape:

// Mashape auth
Unirest\Request::setMashapeKey('');

Otherwise, passing a username, password (optional), defaults to Basic Authentication:

// basic auth
Unirest\Request::auth('username', 'password');

The third parameter, which is a bitmask, will Unirest which HTTP authentication method(s) you want it to use for your proxy authentication.

If more than one bit is set, Unirest (at PHP's libcurl level) will first query the site to see what authentication methods it supports and then pick the best one you allow it to use. For some methods, this will induce an extra network round-trip.

Supported Methods

Method Description
CURLAUTH_BASIC HTTP Basic authentication. This is the default choice
CURLAUTH_DIGEST HTTP Digest authentication. as defined in RFC 2617
CURLAUTH_DIGEST_IE HTTP Digest authentication with an IE flavor. The IE flavor is simply that libcurl will use a special "quirk" that IE is known to have used before version 7 and that some servers require the client to use.
CURLAUTH_NEGOTIATE HTTP Negotiate (SPNEGO) authentication. as defined in RFC 4559
CURLAUTH_NTLM HTTP NTLM authentication. A proprietary protocol invented and used by Microsoft.
CURLAUTH_NTLM_WB NTLM delegating to winbind helper. Authentication is performed by a separate binary application. see libcurl docs for more info
CURLAUTH_ANY This is a convenience macro that sets all bits and thus makes libcurl pick any it finds suitable. libcurl will automatically select the one it finds most secure.
CURLAUTH_ANYSAFE This is a convenience macro that sets all bits except Basic and thus makes libcurl pick any it finds suitable. libcurl will automatically select the one it finds most secure.
CURLAUTH_ONLY This is a meta symbol. OR this value together with a single specific auth value to force libcurl to probe for un-restricted auth and if not, only that single auth algorithm is acceptable.
// custom auth method
Unirest\Request::proxyAuth('username', 'password', CURLAUTH_DIGEST);

Previous versions of Unirest support Basic Authentication by providing the username and password arguments:

$response = Unirest\Request::get('http://mockbin.com/request', null, null, 'username', 'password');

This has been deprecated, and will be completely removed in v.3.0.0 please use the Unirest\Request::auth() method instead

Cookies

Set a cookie string to specify the contents of a cookie header. Multiple cookies are separated with a semicolon followed by a space (e.g., "fruit=apple; colour=red")

Unirest\Request::cookie($cookie)

Set a cookie file path for enabling cookie reading and storing cookies across multiple sequence of requests.

Unirest\Request::cookieFile($cookieFile)

$cookieFile must be a correct path with write permission.

Request Object

Unirest\Request::get($url, $headers = array(), $parameters = null)
Unirest\Request::post($url, $headers = array(), $body = null)
Unirest\Request::put($url, $headers = array(), $body = null)
Unirest\Request::patch($url, $headers = array(), $body = null)
Unirest\Request::delete($url, $headers = array(), $body = null)
  • url - Endpoint, address, or uri to be acted upon and requested information from.
  • headers - Request Headers as associative array or object
  • body - Request Body as associative array or object

You can send a request with any standard or custom HTTP Method:

Unirest\Request::send(Unirest\Method::LINK, $url, $headers = array(), $body);

Unirest\Request::send('CHECKOUT', $url, $headers = array(), $body);

Response Object

Upon recieving a response Unirest returns the result in the form of an Object, this object should always have the same keys for each language regarding to the response details.

  • code - HTTP Response Status Code (Example 200)
  • headers - HTTP Response Headers
  • body - Parsed response body where applicable, for example JSON responses are parsed to Objects / Associative Arrays.
  • raw_body - Un-parsed response body

Advanced Configuration

You can set some advanced configuration to tune Unirest-PHP:

Custom JSON Decode Flags

Unirest uses PHP's JSON Extension for automatically decoding JSON responses. sometime you may want to return associative arrays, limit the depth of recursion, or use any of the customization flags.

To do so, simply set the desired options using the jsonOpts request method:

Unirest\Request::jsonOpts(true, 512, JSON_NUMERIC_CHECK & JSON_FORCE_OBJECT & JSON_UNESCAPED_SLASHES);

Timeout

You can set a custom timeout value (in seconds):

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

Proxy

Set the proxy to use for the upcoming request.

you can also set the proxy type to be one of CURLPROXY_HTTP, CURLPROXY_HTTP_1_0, CURLPROXY_SOCKS4, CURLPROXY_SOCKS5, CURLPROXY_SOCKS4A, and CURLPROXY_SOCKS5_HOSTNAME.

check the cURL docs for more info.

// quick setup with default port: 1080
Unirest\Request::proxy('10.10.10.1');

// custom port and proxy type
Unirest\Request::proxy('10.10.10.1', 8080, CURLPROXY_HTTP);

// enable tunneling
Unirest\Request::proxy('10.10.10.1', 8080, CURLPROXY_HTTP, true);
Proxy Authenticaton

Passing a username, password (optional), defaults to Basic Authentication:

// basic auth
Unirest\Request::proxyAuth('username', 'password');

The third parameter, which is a bitmask, will Unirest which HTTP authentication method(s) you want it to use for your proxy authentication.

If more than one bit is set, Unirest (at PHP's libcurl level) will first query the site to see what authentication methods it supports and then pick the best one you allow it to use. For some methods, this will induce an extra network round-trip.

See Authentication for more details on methods supported.

// basic auth
Unirest\Request::proxyAuth('username', 'password', CURLAUTH_DIGEST);

Default Request Headers

You can set default headers that will be sent on every request:

Unirest\Request::defaultHeader('Header1', 'Value1');
Unirest\Request::defaultHeader('Header2', 'Value2');

You can set default headers in bulk by passing an array:

Unirest\Request::defaultHeaders(array(
    'Header1' => 'Value1',
    'Header2' => 'Value2'
));

You can clear the default headers anytime with:

Unirest\Request::clearDefaultHeaders();

Default cURL Options

You can set default cURL options that will be sent on every request:

Unirest\Request::curlOpt(CURLOPT_COOKIE, 'foo=bar');

You can set options bulk by passing an array:

Unirest\Request::curlOpts(array(
    CURLOPT_COOKIE => 'foo=bar'
));

You can clear the default options anytime with:

Unirest\Request::clearCurlOpts();

SSL validation

You can explicitly enable or disable SSL certificate validation when consuming an SSL protected endpoint:

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

By default is true.

Utility Methods

// alias for `curl_getinfo`
Unirest\Request::getInfo()

// returns internal cURL handle
Unirest\Request::getCurlHandle()

Made with from the Mashape team

Comments
  • Check support for PHP 8

    Check support for PHP 8

    The Travis config does not list PHP 8 as the environment to test in.

    I am wondering whether this library works okay in PHP 8. We should update the tests and the config and ensure PHP 8 compatibility without dropping support for the current support PHP versions.

    opened by thehappybug 2
  • Issue in Http Client while sending multipart form parameters

    Issue in Http Client while sending multipart form parameters

    If we are trying to send form parameters with a mix of both multipart and encoded parameters, then the encoded parameters are not serialized, and json objects got wrongly sent

    bug 
    opened by asadali214 1
  • Only set followlocation if safemode and open_basedir are not set

    Only set followlocation if safemode and open_basedir are not set

    If open_basedir is set, or safe_mode is enabled, then the following error is thrown when attempting to enable FOLLOWLOCATION;

    PHP Warning: curl_setopt_array(): CURLOPT_FOLLOWLOCATION cannot be activated when an open_basedir is set

    I have just added a check to make sure neither of those options are set.

    opened by davidcwhitfield 1
  • Enable manual approvals for new releases

    Enable manual approvals for new releases

    We need to enable approvals for every new release, through Release Reviews. This should be achieved using a GH action for each release

    A quick guide on how to do it: https://cloudlumberjack.com/posts/github-actions-approvals/

    enhancement 
    opened by asadali214 0
  • Inclusion of dependency of core-interfaces-php

    Inclusion of dependency of core-interfaces-php

    • Add dependency of core-interfaces-php after its release
    • Remove support for php 7.1 and below
    • Use all the latest features of php 7.2 and above
    • Make unirest-php ready for the realease of core-lib-php
    enhancement 
    opened by asadali214 0
  • Make http connection persistent

    Make http connection persistent

    Curl should use the already established connection, if there is one. Closes Issue #22.

    Helpful link regarding test: https://curl.se/libcurl/c/CURLINFO_NUM_CONNECTS.html

    opened by Mohammad-Haris 0
  • Move from Travis to GitHub Actions

    Move from Travis to GitHub Actions

    Travis Org is closing down.

    We should move to GitHub Actions. You can check out https://github.com/apimatic/jsonmapper for what a sample GitHub workflow would look like.

    image

    PS: Please take note of issue #8 when doing this.

    opened by thehappybug 0
  • Unit Tests for retries and backoff

    Unit Tests for retries and backoff

    Addition of unit tests for following methods used in calculation of retry and backoff intervals

    1. Request::getRetryWaitTime()
    2. Request::getRetryAfterInSeconds()
    3. Request::sleep()

    Also try to add atleast one test to calculate total wait time while client retries multiple times in order to get a response, this will ensure that retries feature is working properly

    opened by asadali214 0
Releases(4.0.0)
  • 4.0.0(Sep 30, 2022)

    This release brings in the following major changes:

    • The minimum supported PHP version is now 7.2
    • New HttpClient implementation
    • New way set Configurations through HttpConfigurations
    • Improved linting and resolved code analyzer issues
    Source code(tar.gz)
    Source code(zip)
  • 3.0.1(Jul 27, 2022)

  • 3.0.0(Jul 14, 2022)

  • 2.3.0(Jun 15, 2022)

  • 2.2.2(Mar 24, 2022)

  • 2.2.1(Mar 12, 2022)

  • 2.2.0(Mar 10, 2022)

    Changes in this release:

    • Support added to enable or disable retries and backoff for each request that will ignore global httpMethods whitelist.
    • Interface OverrideRetry added to let users choose whether to override retries for next request.

    Now Retries can be configured for next request using these calls:

    1. Unirest\Request::overrideRetryForNextRequest(OverrideRetry::ENABLE_RETRY)
    2. Unirest\Request::overrideRetryForNextRequest(OverrideRetry::DISABLE_RETRY)
    3. Unirest\Request::overrideRetryForNextRequest(OverrideRetry::USE_GLOBAL_SETTINGS)
    Source code(tar.gz)
    Source code(zip)
  • 2.1.0(Nov 12, 2021)

  • 2.0.0(Apr 7, 2020)

    The version 2.* is meant to be fork of mashape/unirest-php for maintainence purposes.

    Changes in this release:

    • Supported PHP versions are now 5.6 to 7.4.
    • PHPUnit version was updated and is now multi-targetted (5, 6, 7).
    • Travis config updated to test against supported PHP versions.
    • Fixes errors when running with 7.4 due to array offset access on integer value.
    Source code(tar.gz)
    Source code(zip)
Owner
APIMatic
Developer Experience Platform for APIs
APIMatic
Unirest in PHP: Simplified, lightweight HTTP client library.

Unirest for PHP Unirest is a set of lightweight HTTP libraries available in multiple languages, built and maintained by Mashape, who also maintain the

Kong 1.3k Dec 28, 2022
List of 77 languages for HTTP statuses

Laravel Lang: HTTP Statuses List of 77 languages for HTTP statuses Installation To get the latest version of Laravel Lang: HTTP Statuses library, simp

Laravel Lang 21 Nov 12, 2022
PHP's lightweight HTTP client

Buzz - Scripted HTTP browser Buzz is a lightweight (<1000 lines of code) PHP 7.1 library for issuing HTTP requests. The library includes three clients

Kris Wallsmith 1.9k Jan 4, 2023
Declarative HTTP Clients using Guzzle HTTP Library and PHP 8 Attributes

Waffler How to install? $ composer require waffler/waffler This package requires PHP 8 or above. How to test? $ composer phpunit Quick start For our e

Waffler 3 Aug 26, 2022
A YOURLS plugin allowing the shortening of multiple URLs with one API request.

Bulk URL Shortening - a YOURLS plugin Plugin for YOURLS Plugin URI: github.com/tdakanalis/bulk_api_bulkshortener Description: A YOURLS plugin allowing

Themistoklis Dakanalis 6 Aug 27, 2022
A super lightweight PSR-7 implementation

PSR-7 implementation A super lightweight PSR-7 implementation. Very strict and very fast. Description Guzzle Laminas Slim Nyholm Lines of code 3.300 3

Tobias Nyholm 972 Jan 5, 2023
Guzzle, an extensible PHP HTTP client

Guzzle, PHP HTTP client Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services. Simple interf

Guzzle 22.3k Jan 2, 2023
Requests for PHP is a humble HTTP request library. It simplifies how you interact with other sites and takes away all your worries.

Requests for PHP Requests is a HTTP library written in PHP, for human beings. It is roughly based on the API from the excellent Requests Python librar

null 3.5k Dec 31, 2022
A Chainable, REST Friendly, PHP HTTP Client. A sane alternative to cURL.

Httpful Httpful is a simple Http Client library for PHP 7.2+. There is an emphasis of readability, simplicity, and flexibility – basically provide the

Nate Good 1.7k Dec 21, 2022
HTTPlug, the HTTP client abstraction for PHP

HTTPlug HTTPlug, the HTTP client abstraction for PHP. Intro HTTP client standard built on PSR-7 HTTP messages. The HTTPlug client interface is compati

The PHP HTTP group 2.4k Dec 30, 2022
PSR-7 HTTP Message implementation

zend-diactoros Repository abandoned 2019-12-31 This repository has moved to laminas/laminas-diactoros. Master: Develop: Diactoros (pronunciation: /dɪʌ

Zend Framework 1.6k Dec 9, 2022
Record your test suite's HTTP interactions and replay them during future test runs for fast, deterministic, accurate tests.

This is a port of the VCR Ruby library to PHP. Record your test suite's HTTP interactions and replay them during future test runs for fast, determinis

php-vcr 1.1k Dec 23, 2022
Requests for PHP is a humble HTTP request library. It simplifies how you interact with other sites and takes away all your worries.

Requests for PHP Requests is a HTTP library written in PHP, for human beings. It is roughly based on the API from the excellent Requests Python librar

null 3.5k Dec 31, 2022
The HttpClient component provides powerful methods to fetch HTTP resources synchronously or asynchronously.

HttpClient component The HttpClient component provides powerful methods to fetch HTTP resources synchronously or asynchronously. Resources Documentati

Symfony 1.7k Jan 6, 2023
PSR HTTP Message implementations

laminas-diactoros Diactoros (pronunciation: /dɪʌktɒrɒs/): an epithet for Hermes, meaning literally, "the messenger." This package supercedes and repla

Laminas Project 343 Dec 25, 2022
PHP Curl Class makes it easy to send HTTP requests and integrate with web APIs

PHP Curl Class: HTTP requests made easy PHP Curl Class makes it easy to send HTTP requests and integrate with web APIs. Installation Requirements Quic

null 3.1k Jan 5, 2023
The HttpFoundation component defines an object-oriented layer for the HTTP specification.

HttpFoundation Component The HttpFoundation component defines an object-oriented layer for the HTTP specification. Resources Documentation Contributin

Symfony 8.3k Dec 29, 2022
HTTP header kit for PHP 7.1+ (incl. PHP 8) based on PSR-7

HTTP header kit for PHP 7.1+ (incl. PHP 8) based on PSR-7 Installation composer require sunrise/http-header-kit How to use? HTTP Header Collection Mor

Sunrise // PHP 63 Dec 31, 2022
↪️ Bypass for PHP creates a custom HTTP Server to return predefined responses to client requests

Bypass for PHP provides a quick way to create a custom HTTP Server to return predefined responses to client requests.Useful for tests with Pest PHP or PHPUnit.

CiaReis 101 Dec 1, 2022