Class HttpSocket

CakePHP network socket connection class.

Core base class for HTTP network communication. HttpSocket can be used as an Object Oriented replacement for cURL in many places.

CakeSocket
Extended by HttpSocket
Package: Cake\Network\Http
Copyright: Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
License: MIT License
Location: Cake/Network/Http/HttpSocket.php

Properties summary

  • $_auth protected
    array
    Authentication settings
  • $_contentResource protected
    mixed
    Resource to receive the content of request
  • $_proxy protected
    array
    Proxy settings
  • $config public
    array
    Configuration settings for the HttpSocket and the requests
  • $quirksMode public
    boolean

    When one activates the $quirksMode by setting it to true, all checks meant to enforce RFC 2616 (HTTP/1.1 specs). will be disabled and additional measures to deal with non-standard responses will be enabled.

  • $request public
    array
    Contain information about the last request (read only)
  • $response public
    array
    Contain information about the last response (read only)
  • string
    Response class name

Inherited Properties

Method Summary

  • __construct() public
    Build an HTTP Socket using the specified configuration.
  • _buildHeader() protected
    Builds the header.
  • Builds a request line according to HTTP/1.1 specs. Activate quirks mode to work outside specs.
  • _buildUri() protected
    Takes a $uri array and turns it into a fully qualified URL string
  • _configUri() protected
    Parses and sets the specified URI into current request configuration.
  • _escapeToken() protected
    Escapes a given $token according to RFC 2616 (HTTP 1.1 specs)
  • _parseQuery() protected

    This function can be thought of as a reverse to PHP5's http_build_query(). It takes a given query string and turns it into an array and supports nesting by using the php bracket syntax. So this means you can parse queries like:

  • _parseUri() protected

    Parses the given URI and breaks it down into pieces as an indexed array with elements such as 'scheme', 'port', 'query'.

  • _setAuth() protected
    Set authentication in request
  • _setProxy() protected
    Set the proxy configuration and authentication
  • Gets escape chars according to RFC 2616 (HTTP 1.1 specs).
  • Builds cookie headers for a request.
  • configAuth() public
    Set authentication settings.
  • configProxy() public
    Set proxy settings
  • delete() public
    Issues a DELETE request to the specified URI, query, and request.
  • get() public
    Issues a GET request to the specified URI, query, and request.
  • head() public
    Issues a HEAD request to the specified URI, query, and request.
  • patch() public
    Issues a PATCH request to the specified URI, query, and request.
  • post() public
    Issues a POST request to the specified URI, query, and request.
  • put() public
    Issues a PUT request to the specified URI, query, and request.
  • request() public

    Issue the specified request. HttpSocket::get() and HttpSocket::post() wrap this method and provide a more granular interface.

  • reset() public

    Resets the state of this HttpSocket instance to it's initial state (before CakeObject::__construct got executed) or does the same thing partially for the request and the response property only.

  • Set the resource to receive the request content. This resource must support fwrite.
  • url() public

    Normalizes URLs into a $uriTemplate. If no template is provided a default one will be used. Will generate the URL using the current config information.

Method Detail

__construct()source public

__construct( string|array $config array() )

Build an HTTP Socket using the specified configuration.

You can use a URL string to set the URL and use default configurations for all other options:

$http = new HttpSocket('https://cakephp.org/');

Or use an array to configure multiple options:

$http = new HttpSocket(array(
   'host' => 'cakephp.org',
   'timeout' => 20
));

See HttpSocket::$config for options that can be used.

Parameters

string|array $config optional array()
Configuration information, either a string URL or an array of options.

Overrides

CakeSocket::__construct()

_buildHeader()source protected

_buildHeader( array $header , string $mode 'standard' )

Builds the header.

Parameters

array $header
Header to build
string $mode optional 'standard'
Mode

Returns

string
Header built from array

_buildRequestLine()source protected

_buildRequestLine( array $request array() )

Builds a request line according to HTTP/1.1 specs. Activate quirks mode to work outside specs.

Parameters

array $request optional array()
Needs to contain a 'uri' key. Should also contain a 'method' key, otherwise defaults to GET.

Returns

string
Request line

Throws

SocketException

_buildUri()source protected

_buildUri( string|array $uri array() , string $uriTemplate '%scheme://%user:%pass@%host:%port/%path?%query#%fragment' )

Takes a $uri array and turns it into a fully qualified URL string

Parameters

string|array $uri optional array()
Either A $uri array, or a request string. Will use $this->config if left empty.
string $uriTemplate optional '%scheme://%user:%pass@%host:%port/%path?%query#%fragment'
The Uri template/format to use.

Returns

mixed
A fully qualified URL formatted according to $uriTemplate, or false on failure

_configUri()source protected

_configUri( string|array $uri null )

Parses and sets the specified URI into current request configuration.

Parameters

string|array $uri optional null
URI, See HttpSocket::_parseUri()

Returns

boolean
If uri has merged in config

_escapeToken()source protected

_escapeToken( string $token , array $chars null )

Escapes a given $token according to RFC 2616 (HTTP 1.1 specs)

Parameters

string $token
Token to escape
array $chars optional null
Characters to escape

Returns

string
Escaped token

_parseQuery()source protected

_parseQuery( string|array $query )

This function can be thought of as a reverse to PHP5's http_build_query(). It takes a given query string and turns it into an array and supports nesting by using the php bracket syntax. So this means you can parse queries like:

  • ?key[subKey]=value
  • ?key[]=value1&key[]=value2

A leading '?' mark in $query is optional and does not effect the outcome of this function. For the complete capabilities of this implementation take a look at HttpSocketTest::testparseQuery()

Parameters

string|array $query
A query string to parse into an array or an array to return directly "as is"

Returns

array

The $query parsed into a possibly multi-level array. If an empty $query is given, an empty array is returned.


_parseUri()source protected

_parseUri( string|array $uri null , boolean|array $base array() )

Parses the given URI and breaks it down into pieces as an indexed array with elements such as 'scheme', 'port', 'query'.

Parameters

string|array $uri optional null
URI to parse
boolean|array $base optional array()
If true use default URI config, otherwise indexed array to set 'scheme', 'host', 'port', etc.

Returns

array
Parsed URI

_setAuth()source protected

_setAuth( )

Set authentication in request

Throws

SocketException

_setProxy()source protected

_setProxy( )

Set the proxy configuration and authentication

Throws

SocketException

_tokenEscapeChars()source protected

_tokenEscapeChars( boolean $hex true , array $chars null )

Gets escape chars according to RFC 2616 (HTTP 1.1 specs).

Parameters

boolean $hex optional true
true to get them as HEX values, false otherwise
array $chars optional null
Characters to escape

Returns

array
Escape chars

buildCookies()source public

buildCookies( array $cookies )

Builds cookie headers for a request.

Cookies can either be in the format returned in responses, or a simple key => value pair.

Parameters

array $cookies
Array of cookies to send with the request.

Returns

string
Cookie header string to be sent with the request.

configAuth()source public

configAuth( string $method , string|array $user null , string $pass null )

Set authentication settings.

Accepts two forms of parameters. If all you need is a username + password, as with Basic authentication you can do the following:

$http->configAuth('Basic', 'mark', 'secret');

If you are using an authentication strategy that requires more inputs, like Digest authentication you can call configAuth() with an array of user information.

$http->configAuth('Digest', array(
    'user' => 'mark',
    'pass' => 'secret',
    'realm' => 'my-realm',
    'nonce' => 1235
));

To remove any set authentication strategy, call configAuth() with no parameters:

$http->configAuth();

Parameters

string $method
Authentication method (ie. Basic, Digest). If empty, disable authentication
string|array $user optional null
Username for authentication. Can be an array with settings to authentication class
string $pass optional null
Password for authentication

configProxy()source public

configProxy( string|array $host , integer $port 3128 , string $method null , string $user null , string $pass null )

Set proxy settings

Parameters

string|array $host
Proxy host. Can be an array with settings to authentication class
integer $port optional 3128
Port. Default 3128.
string $method optional null
Proxy method (ie, Basic, Digest). If empty, disable proxy authentication
string $user optional null
Username if your proxy need authentication
string $pass optional null
Password to proxy authentication

delete()source public

delete( string|array $uri null , array $data array() , array $request array() )

Issues a DELETE request to the specified URI, query, and request.

Parameters

string|array $uri optional null
URI to request (see HttpSocket::_parseUri())
array $data optional array()
Array of request body data keys and values.
array $request optional array()
An indexed array with indexes such as 'method' or uri

Returns

mixed
Result of request

get()source public

get( string|array $uri null , array $query array() , array $request array() )

Issues a GET request to the specified URI, query, and request.

Using a string uri and an array of query string parameters:

$response = $http->get('http://google.com/search', array('q' => 'cakephp', 'client' => 'safari'));

Would do a GET request to http://google.com/search?q=cakephp&client=safari

You could express the same thing using a uri array and query string parameters:

$response = $http->get(
    array('host' => 'google.com', 'path' => '/search'),
    array('q' => 'cakephp', 'client' => 'safari')
);

Parameters

string|array $uri optional null
URI to request. Either a string uri, or a uri array, see HttpSocket::_parseUri()
array $query optional array()
Querystring parameters to append to URI
array $request optional array()
An indexed array with indexes such as 'method' or uri

Returns

mixed
Result of request, either false on failure or the response to the request.

head()source public

head( string|array $uri null , array $query array() , array $request array() )

Issues a HEAD request to the specified URI, query, and request.

By definition HEAD request are identical to GET request except they return no response body. This means that all information and examples relevant to GET also applys to HEAD.

Parameters

string|array $uri optional null
URI to request. Either a string URI, or a URI array, see HttpSocket::_parseUri()
array $query optional array()
Querystring parameters to append to URI
array $request optional array()
An indexed array with indexes such as 'method' or uri

Returns

mixed
Result of request, either false on failure or the response to the request.

patch()source public

patch( string|array $uri null , array $data array() , array $request array() )

Issues a PATCH request to the specified URI, query, and request.

Parameters

string|array $uri optional null
URI to request, See HttpSocket::_parseUri()
array $data optional array()
Array of request body data keys and values.
array $request optional array()
An indexed array with indexes such as 'method' or uri

Returns

mixed
Result of request

post()source public

post( string|array $uri null , array $data array() , array $request array() )

Issues a POST request to the specified URI, query, and request.

post() can be used to post simple data arrays to a URL:

$response = $http->post('http://example.com', array(
    'username' => 'batman',
    'password' => 'bruce_w4yne'
));

Parameters

string|array $uri optional null
URI to request. See HttpSocket::_parseUri()
array $data optional array()
Array of request body data keys and values.
array $request optional array()
An indexed array with indexes such as 'method' or uri

Returns

mixed
Result of request, either false on failure or the response to the request.

put()source public

put( string|array $uri null , array $data array() , array $request array() )

Issues a PUT request to the specified URI, query, and request.

Parameters

string|array $uri optional null
URI to request, See HttpSocket::_parseUri()
array $data optional array()
Array of request body data keys and values.
array $request optional array()
An indexed array with indexes such as 'method' or uri

Returns

mixed
Result of request

request()source public

request( string|array $request array() )

Issue the specified request. HttpSocket::get() and HttpSocket::post() wrap this method and provide a more granular interface.

Parameters

string|array $request optional array()
Either an URI string, or an array defining host/uri

Returns

mixed
false on error, HttpSocketResponse on success

Throws

SocketException

reset()source public

reset( boolean $full true )

Resets the state of this HttpSocket instance to it's initial state (before CakeObject::__construct got executed) or does the same thing partially for the request and the response property only.

Parameters

boolean $full optional true
If set to false only HttpSocket::response and HttpSocket::request are reset

Returns

boolean
True on success

Overrides

CakeSocket::reset()

setContentResource()source public

setContentResource( resource|boolean $resource )

Set the resource to receive the request content. This resource must support fwrite.

Parameters

resource|boolean $resource
Resource or false to disable the resource use

Throws

SocketException

url()source public

url( string|array $url null , string $uriTemplate null )

Normalizes URLs into a $uriTemplate. If no template is provided a default one will be used. Will generate the URL using the current config information.

Usage:

After configuring part of the request parameters, you can use url() to generate URLs.

$http = new HttpSocket('https://www.cakephp.org');
$url = $http->url('/search?q=bar');

Would return https://cakephp.org/search?q=bar

url() can also be used with custom templates:

$url = $http->url('http://www.cakephp/search?q=socket', '/%path?%query');

Would return /search?q=socket.

Parameters

string|array $url optional null
Either a string or array of URL options to create a URL with.
string $uriTemplate optional null
A template string to use for URL formatting.

Returns

mixed
Either false on failure or a string containing the composed URL.

Methods inherited from CakeSocket

__destruct()source public

__destruct( )

Destructor, used to disconnect from current connection.

_addTlsVersions()source protected

_addTlsVersions( )

Add TLS versions that are dependent on specific PHP versions.

These TLS versions are not supported by older PHP versions, so we have to conditionally set them if they are supported.

As of PHP5.6.6, STREAM_CRYPTO_METHOD_TLS_CLIENT does not include TLS1.1 or 1.2. If we have TLS1.2 support we need to update the method map.

See

https://bugs.php.net/bug.php?id=69195
https://github.com/php/php-src/commit/10bc5fd4c4c8e1dd57bd911b086e9872a56300a0

_connectionErrorHandler()source protected

_connectionErrorHandler( integer $code , string $message )

socket_stream_client() does not populate errNum, or $errStr when there are connection errors, as in the case of SSL verification failure.

Instead we need to handle those errors manually.

Parameters

integer $code
Code.
string $message
Message.

_setSslContext()source protected

_setSslContext( string $host )

Configure the SSL context options.

Parameters

string $host
The host name being connected to.

address()source public

address( )

Gets the IP address of the current connection.

Returns

string
IP address

addresses()source public

addresses( )

Gets all IP addresses associated with the current connection.

Returns

array
IP addresses

connect()source public

connect( )

Connects the socket to the given host and port.

Returns

boolean
Success

Throws

SocketException

context()source public

context( )

Gets the connection context.

Returns

null|array
Null when there is no connection, an array when there is.

disconnect()source public

disconnect( )

Disconnects the socket from the current connection.

Returns

boolean
Success

enableCrypto()source public

enableCrypto( string $type , string $clientOrServer 'client' , boolean $enable true )

Encrypts current stream socket, using one of the defined encryption methods.

Parameters

string $type
Type which can be one of 'sslv2', 'sslv3', 'sslv23', 'tls', 'tlsv1_1' or 'tlsv1_2'.
string $clientOrServer optional 'client'
Can be one of 'client', 'server'. Default is 'client'.
boolean $enable optional true
Enable or disable encryption. Default is true (enable)

Returns

boolean
True on success

Throws

InvalidArgumentException
When an invalid encryption scheme is chosen.
SocketException
When attempting to enable SSL/TLS fails.

See

stream_socket_enable_crypto

host()source public

host( )

Gets the host name of the current connection.

Returns

string
Host name

lastError()source public

lastError( )

Gets the last error as a string.

Returns

string|null
Last error

read()source public

read( integer $length 1024 )

Reads data from the socket. Returns false if no data is available or no connection could be established.

Parameters

integer $length optional 1024
Optional buffer length to read; defaults to 1024

Returns

mixed
Socket data

setLastError()source public

setLastError( integer $errNum , string $errStr )

Sets the last error.

Parameters

integer $errNum
Error code
string $errStr
Error string

write()source public

write( string $data )

Writes data to the socket.

Parameters

string $data
The data to write to the socket

Returns

boolean
Success

Properties detail

$_authsource

protected array

Authentication settings

array()

$_contentResourcesource

protected mixed

Resource to receive the content of request

null

$_proxysource

protected array

Proxy settings

array()

$configsource

public array

Configuration settings for the HttpSocket and the requests

array(
    'persistent' => false,
    'host' => 'localhost',
    'protocol' => 'tcp',
    'port' => 80,
    'timeout' => 30,
    'ssl_verify_peer' => true,
    'ssl_allow_self_signed' => false,
    'ssl_verify_depth' => 5,
    'ssl_verify_host' => true,
    'request' => array(
        'uri' => array(
            'scheme' => array('http', 'https'),
            'host' => 'localhost',
            'port' => array(80, 443)
        ),
        'redirect' => false,
        'cookies' => array(),
    )
)

$quirksModesource

public boolean

When one activates the $quirksMode by setting it to true, all checks meant to enforce RFC 2616 (HTTP/1.1 specs). will be disabled and additional measures to deal with non-standard responses will be enabled.

false

$requestsource

public array

Contain information about the last request (read only)

array(
    'method' => 'GET',
    'uri' => array(
        'scheme' => 'http',
        'host' => null,
        'port' => 80,
        'user' => null,
        'pass' => null,
        'path' => null,
        'query' => null,
        'fragment' => null
    ),
    'version' => '1.1',
    'body' => '',
    'line' => null,
    'header' => array(
        'Connection' => 'close',
        'User-Agent' => 'CakePHP'
    ),
    'raw' => null,
    'redirect' => false,
    'cookies' => array(),
)

$responsesource

public array

Contain information about the last response (read only)

null

$responseClasssource

public string

Response class name

'HttpSocketResponse'

© 2005–2017 The Cake Software Foundation, Inc.
Licensed under the MIT License.
CakePHP is a registered trademark of Cake Software Foundation, Inc.
We are not endorsed by or affiliated with CakePHP.
https://api.cakephp.org/2.10/class-HttpSocket.html