HttpSocket (class)

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. (http://cakefoundation.org)
License: MIT License
Located at Cake/Network/Http/HttpSocket.php

Method Detail

__constructsource 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('http://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()

_buildHeadersource 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

_buildRequestLinesource 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
SocketException

_buildUrisource 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

_configUrisource 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

_escapeTokensource 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

_parseQuerysource 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.

_parseUrisource 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

_setAuthsource protected

_setAuth( )

Set authentication in request

Throws

SocketException
SocketException

_setProxysource protected

_setProxy( )

Set the proxy configuration and authentication

Throws

SocketException
SocketException

_tokenEscapeCharssource 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

buildCookiessource 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.

configAuthsource 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

configProxysource 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

deletesource 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

getsource 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.

headsource 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.

patchsource 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

postsource 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.

putsource 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

requestsource 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
SocketException

resetsource public

reset( boolean $full true )

Resets the state of this HttpSocket instance to it's initial state (before Object::__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()

setContentResourcesource 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
SocketException

urlsource 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('http://www.cakephp.org');
$url = $http->url('/search?q=bar');

Would return http://www.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

__destructsource public

__destruct( )

Destructor, used to disconnect from current connection.

_connectionErrorHandlersource 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.

_setSslContextsource protected

_setSslContext( string $host )

Configure the SSL context options.

Parameters

string $host
The host name being connected to.

addresssource public

address( )

Gets the IP address of the current connection.

Returns

string
IP address

addressessource public

addresses( )

Gets all IP addresses associated with the current connection.

Returns

array
IP addresses

connectsource public

connect( )

Connects the socket to the given host and port.

Returns

boolean
Success

Throws

SocketException
SocketException

contextsource public

context( )

Gets the connection context.

Returns

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

disconnectsource public

disconnect( )

Disconnects the socket from the current connection.

Returns

boolean
Success

enableCryptosource 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' or 'tls'.
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

hostsource public

host( )

Gets the host name of the current connection.

Returns

string
Host name

lastErrorsource public

lastError( )

Gets the last error as a string.

Returns

string|null
Last error

readsource 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

setLastErrorsource public

setLastError( integer $errNum , string $errStr )

Sets the last error.

Parameters

integer $errNum
Error code
string $errStr
Error string

writesource public

write( string $data )

Writes data to the socket.

Parameters

string $data
The data to write to the socket

Returns

boolean
Success

Properties summary

$_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'

Properties inherited from CakeSocket

$_baseConfigsource

protected array

Base configuration settings for the socket connection

array(
    'persistent' => false,
    'host' => 'localhost',
    'protocol' => 'tcp',
    'port' => 80,
    'timeout' => 30
)

$_connectionErrorssource

protected array

Used to capture connection warnings which can happen when there are SSL errors for example.

array()

$_encryptMethodssource

protected array

Contains all the encryption methods available

array(
    // @codingStandardsIgnoreStart
    'sslv2_client' => STREAM_CRYPTO_METHOD_SSLv2_CLIENT,
    'sslv3_client' => STREAM_CRYPTO_METHOD_SSLv3_CLIENT,
    'sslv23_client' => STREAM_CRYPTO_METHOD_SSLv23_CLIENT,
    'tls_client' => STREAM_CRYPTO_METHOD_TLS_CLIENT,
    'sslv2_server' => STREAM_CRYPTO_METHOD_SSLv2_SERVER,
    'sslv3_server' => STREAM_CRYPTO_METHOD_SSLv3_SERVER,
    'sslv23_server' => STREAM_CRYPTO_METHOD_SSLv23_SERVER,
    'tls_server' => STREAM_CRYPTO_METHOD_TLS_SERVER
    // @codingStandardsIgnoreEnd
)

$connectedsource

public boolean

This boolean contains the current state of the CakeSocket class

false

$connectionsource

public resource

Reference to socket connection resource

null

$descriptionsource

public string

Object description

'Remote DataSource Network Socket Interface'

$encryptedsource

public boolean

True if the socket stream is encrypted after a CakeSocket::enableCrypto() call

false

$lastErrorsource

public array

This variable contains an array with the last error number (num) and string (str)

array()

© 2005–2016 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.
http://api.cakephp.org/2.7/class-HttpSocket.html

在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号

意见反馈
返回顶部