Class HttpSocket
Cake 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
- HttpSocket
Copyright: Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
License: MIT License
Location: Cake/Network/Http/HttpSocket.php
Properties summary
-
$_auth
protectedarray
Authentication settings -
$_contentResource
protectedmixed
Resource to receive the content of request -
$_proxy
protectedarray
Proxy settings -
$config
publicarray
Configuration settings for the HttpSocket and the requests -
$quirksMode
publicboolean
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
publicarray
Contain information about the last request (read only) -
$response
publicarray
Contain information about the last response (read only) -
$responseClass
publicstring
Response classname
Inherited Properties
Method Summary
-
__construct() public
Build an HTTP Socket using the specified configuration. -
_buildHeader() protected
Builds the header. -
_buildRequestLine() protected
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 -
_configContext() protected
Configure the socket's context. Adds in configuration that can not be declared in the class definition.
-
_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 -
_tokenEscapeChars() protected
Gets escape chars according to RFC 2616 (HTTP 1.1 specs). -
buildCookies() public
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. -
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 Object::__construct got executed) or does the same thing partially for the request and the response property only.
-
setContentResource() public
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() public ¶
__construct( string|array $config = array() )
Build an HTTP Socket using the specified configuration.
You can use an 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
_buildHeader() protected ¶
_buildHeader( array $header , string $mode = 'standard' )
Builds the header.
Parameters
- array $header
- Header to build
- string $mode optional 'standard'
Returns
Header built from array
_buildRequestLine() protected ¶
_buildRequestLine( array $request = array() , string $versionToken = 'HTTP/1.1' )
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.
- string $versionToken optional 'HTTP/1.1'
- The version token to use, defaults to HTTP/1.1
Returns
Request line
Throws
_buildUri() 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
A fully qualified URL formatted according to $uriTemplate, or false on failure
_configContext() protected ¶
_configContext( string $host )
Configure the socket's context. Adds in configuration that can not be declared in the class definition.
Parameters
- string $host
- The host you're connecting to.
_configUri() 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
If uri has merged in config
_escapeToken() 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
Returns
Escaped token
_parseQuery() 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
The $query parsed into a possibly multi-level array. If an empty $query is given, an empty array is returned.
_parseUri() 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
Parsed URI
_tokenEscapeChars() 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
Returns
Escape chars
buildCookies() 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
Cookie header string to be sent with the request.
configAuth() 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() 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() 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()
- Query to append to URI
- array $request optional array()
- An indexed array with indexes such as 'method' or uri
Returns
Result of request
get() 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
Result of request, either false on failure or the response to the request.
post() 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 an 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 POST data keys and values.
- array $request optional array()
- An indexed array with indexes such as 'method' or uri
Returns
Result of request, either false on failure or the response to the request.
put() 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 PUT data keys and values.
- array $request optional array()
- An indexed array with indexes such as 'method' or uri
Returns
Result of request
request() 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
false on error, HttpSocketResponse on success
Throws
reset() 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 reseted
Returns
True on success
Overrides
setContentResource() 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
url() 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
- a string or array of URL options to create an URL with.
- string $uriTemplate optional null
- A template string to use for URL formatting.
Returns
Either false on failure or a string containing the composed URL.
Methods inherited from CakeSocket
_connectionErrorHandler() 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
- string $message
address() public ¶
address( )
Get the IP address of the current connection.
Returns
IP address
addresses() public ¶
addresses( )
Get all IP addresses associated with the current connection.
Returns
IP addresses
context() public ¶
context( )
Get the connection context.
Returns
Null when there is no connection, an array when there is.
disconnect() public ¶
disconnect( )
Disconnect the socket from the current connection.
Returns
Success
enableCrypto() public ¶
enableCrypto( string $type , string $clientOrServer = 'client' , boolean $enable = true )
Encrypts current stream socket, using one of the defined encryption methods
Parameters
- string $type
- can be one of 'ssl2', 'ssl3', 'ssl23' 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
True on success
Throws
When an invalid encryption scheme is chosen.
SocketException
When attempting to enable SSL/TLS fails
See
read() public ¶
read( integer $length = 1024 )
Read 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
Socket data
setLastError() public ¶
setLastError( integer $errNum , string $errStr )
Set the last error.
Parameters
- integer $errNum
- Error code
- string $errStr
- Error string
Properties detail
$config ¶
Configuration settings for the HttpSocket and the requests
array( 'persistent' => false, 'host' => 'localhost', 'protocol' => 'tcp', 'port' => 80, 'timeout' => 30, 'ssl_verify_peer' => true, '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(), ) )
$quirksMode ¶
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
$request ¶
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(), )