sFire PHP Framework

HTTP Client

sFire\HTTP\Client provides an easy interface for performing Hyper-Text Transfer Protocol (HTTP) requests. sFire\HTTP\Client supports the most simple features expected from an HTTP client, as well as some more complex features such as HTTP authentication and file uploads.

Note: The HTTP Client is build on PHP's libcurl and open_ssl libraries.

In this section we will handle:

  • Creating a new instance
  • All the request methods like get, post, put, delete, etc.
  • Uploading files in your request
  • Add cookies to the request
  • Retrieve the response
  • Authentication
  • Setting different kind of options like the User Agent and timeouts

Creating a new instance

To use the HTTP client you should create a new instance:

use sFire\HTTP\Client;

$client = new Client();

Request methods

To create a (RESTful) HTTP request you may use on of the get, post, put, delete, patch, head, options, trace, connect methods. All these methods are universal in use.

Parameters
$client -> get(string $domain, [function $callback]);
$client -> post(string $domain, [function $callback]);
$client -> put(string $domain, [function $callback]);
$client -> delete(string $domain, [function $callback]);
$client -> patch(string $domain, [function $callback]);
$client -> head(string $domain, [function $callback]);
$client -> options(string $domain, [function $callback]);
$client -> trace(string $domain, [function $callback]);
$client -> connect(string $domain, [function $callback]);

To create a GET request you can simply pass the domain as a string to the get method:

$client -> get('http://example.org');

You may pass a callable function to set more options before sending the request. The callable function will be injected with a sFire\HTTP\Client instance variable for you to set new options:

$client -> get('http://example.org', function($http) {
    $http -> addParam('foo', 'bar');
    $http -> addCookie('foo', 'bar');
});

In this example the requested URL will be "http://example.org?foo=bar" and the headers will be injected with a cookie named "foo" with value "bar".

Uploading files

To upload a file or multiple files to the requested URL you need to call the addFile method. The first parameter is the path to the file, second parameter is an optional new name for the file and the third optional parameter is a new MIME type.

$client -> post('http://example.org', function($http) {
    $http -> addFile('foo.txt');
    $http -> addFile('bar.txt', 'newname.txt', 'plain/text');
});

sFire will try to detect the MIME type if non given.

Note: Only the POST method is allowed to upload files.

Add cookies

To send cookie(s) with a request you can use the addCookie method. The first parameter will be the name and the second parameter is the content of the cookie.

$client -> get('http://example.org', function($http) {
    $http -> addCookie('foo', 'bar');
});

Retrieve the response

The response of a request can be divided by four items; response headers, response status code, response body and response cookies (part of the response headers).

Retrieve response headers

This will return an Array with information about the returned headers.

$client = new Client();
$client -> get('http://example.org');
print_r($client -> getHeaders());

//Output similar to:
Array
(
    [cache-control] => private, max-age=0
    [content-type] => text/html; charset=ISO-8859-1
    [x-xss-protection] => 1; mode=block
    [x-frame-options] => SAMEORIGIN
    [accept-ranges] => none
    [vary] => Accept-Encoding
    [transfer-encoding] => chunked
)

Retrieve status code

This will return an Array with information about the returned status.

$client -> get('http://example.org');
print_r($client -> getStatus());

//Output similar to:
Array
(
    [code] => 200
    [protocol] => HTTP/1.1
    [status] => HTTP/1.1 200 OK
    [text] => OK
)

Retrieve response body

This will return the body of the response as a string.

$client -> get('http://example.org');
print_r($client -> getBody());

Convert response body to JSON

If you know for sure that the response will be given as a JSON string, you can use the getJson method to convert the response automatically to JSON.

$client -> get('http://example.org');
print_r($client -> getJson());

Retrieve response cookies

This will return an Array with information about all the returned cookies.

$client -> get('http://example.org');
print_r($client -> getCookies());

Retrieve more detailed information

This will return an Array with more detailed information

$client -> get('http://example.org');
print_r($client -> getInfo());

//Output similar to:
Array
(
    [url] => http://www.example.org/
    [content_type] => text/html; charset=ISO-8859-1
    [http_code] => 200
    [header_size] => 638
    [request_size] => 62
    [filetime] => -1
    [ssl_verify_result] => 0
    [redirect_count] => 0
    [total_time] => 0.141675
    [namelookup_time] => 0.028429
    [connect_time] => 0.042713
    [pretransfer_time] => 0.042736
    [size_upload] => 0
    [size_download] => 46977
    [speed_download] => 331582
    [speed_upload] => 0
    [download_content_length] => -1
    [upload_content_length] => 0
    [starttransfer_time] => 0.105057
    [redirect_time] => 0
    [redirect_url] => 
    [primary_port] => 80
    [local_port] => 36817
)

Add custom headers

You may use the "addHeader" method to set custom headers. The first parameter is the header name without the need of a colon :. The second parameter is the value of the header as a string.

$client -> get('http://example.org', function($http) {
    $http -> addHeader('Connection', 'keep-alive');
});

Authentication

To set an authentication you can use the authenticate method:

$client -> get('http://example.org', function($http) {
    $http -> authenticate('username', 'password', Client :: AUTH_BASIC);
});

You can use different kind of authentication with your request:

  • AUTH_BASIC

    HTTP Basic authentication. This is the default choice, and the only method that is in wide-spread use and supported virtually everywhere. This sends the user name and password over the network in plain text, easily captured by others.

  • AUTH_DIGEST

    HTTP Digest authentication. Digest authentication is defined in RFC 2617 and is a more secure way to do authentication over public networks than the regular old-fashioned Basic method.

  • AUTH_GSSNEGOTIATE

    HTTP Negotiate (SPNEGO) authentication. Negotiate authentication is defined in RFC 4559 and is the most secure way to perform authentication over HTTP.

  • AUTH_NTLM

    HTTP NTLM authentication. A proprietary protocol invented and used by Microsoft. It uses a challenge-response and hash concept similar to Digest, to prevent the password from being eavesdropped.

  • AUTH_ANY

    This is a convenience macro that sets all bits and thus makes it pick any it finds suitable. It will automatically select the one it finds most secure.

  • AUTH_ANYSAFE

    This is a convenience macro that sets all bits except Basic and thus makes it pick any it finds suitable. It will automatically select the one it finds most secure.

Options

You can set many extra options to be included in the request.

Set port

The default port (80) can be overruled by setting it with the port method. The first and only parameter will be an Integer with the new port.

$client -> get('http://example.org', function($http) {
    $http -> port(8080);
});

Set connection timeout and read timeout

The default timeout for the connection (30 seconds) and response (30 seconds) can be overruled by setting it with the timeout method.

This method takes two parameters. The first parameter is the connection timeout and is an Integer in seconds for the timeout in making the initial connection; i.e. completing the TCP connection handshake. The second parameter is the read timeout as an Integer in seconds and is the timeout on waiting to read data.

$client -> get('http://example.org', function($http) {
    $http -> timeout(10, 15);
});

Set referer

You may set a new referer (default null) as the first and only parameter of the referer method:

$client -> get('http://example.org', function($http) {
    $http -> referer('google.com');
});

Set HTTP User Agent

You may set a new User Agent (default null) as the first and only parameter of the referer method:

$client -> get('http://example.org', function($http) {
    $http -> userAgent('Mozilla/5.0 (Windows NT 6.1)');
});

Set HTTP version

To set a new HTTP version, you may use the httpVersion method like in the example below:

$client -> get('http://example.org', function($http) {
    $http -> httpVersion(Client :: HTTP_2_0);
});

You can set different HTTP protocol version:

  • HTTP_1_0

    Enforce HTTP 1.0 requests.

  • HTTP_1_1

    Enforce HTTP 1.1 requests (default).

  • HTTP_2_0

    Attempt HTTP 2 requests. Will fall back to HTTP 1.1 if HTTP 2 can't be negotiated with the server.

  • HTTP_2TLS

    Attempt HTTP 2 over TLS (HTTPS) only. Will fall back to HTTP 1.1 if HTTP 2 can't be negotiated with the HTTPS server. For clear text HTTP servers, it will use 1.1.

  • HTTP_2_PRIOR_KNOWLEDGE

    Issue non-TLS HTTP requests using HTTP/2 without HTTP/1.1 Upgrade. It requires prior knowledge that the server supports HTTP/2 straight away. HTTPS requests will still do HTTP/2 the standard way with negotiated protocol version in the TLS handshake.

Set maximum redirects to follow

You may set a new maximum redirect to follow. Set the first and only Integer parameter of the follow method:

$client -> get('http://example.org', function($http) {
    $http -> follow(10);
});