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.
- Object
- CakeSocket
- HttpSocket
Copyright: Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
License: License (http://www.opensource.org/licenses/mit-license.php)
Location: http_socket.php
Properties summary
-
$config
publicarray
Default configuration settings for the HttpSocket -
$description
publicstring
Object description -
$lineBreak
publicstring
String that represents a line break. -
$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
The default values to use for a request -
$response
publicarray
The default structure for storing the response
Inherited Properties
Method Summary
-
__construct() public
Build an HTTP Socket using the specified configuration. -
_buildHeader() public
Builds the header. -
_buildRequestLine() public
Builds a request line according to HTTP/1.1 specs. Activate quirks mode to work outside specs. -
_buildUri() public
Takes a $uri array and turns it into a fully qualified URL string -
_configUri() public
Parses and sets the specified URI into current request configuration. -
_decodeBody() public
Generic function to decode a $body with a given $encoding. Returns either an array with the keys 'body' and 'header' or false on failure.
-
_decodeChunkedBody() public
Decodes a chunked message $body and returns either an array with the keys 'body' and 'header' or false as a result.
-
_escapeToken() public
Escapes a given $token according to RFC 2616 (HTTP 1.1 specs) -
_httpSerialize() public
Serializes an array for transport. -
_parseHeader() public
Parses an array based header. -
_parseQuery() public
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 menas you can parse queries like:
-
_parseResponse() public
Parses the given message and breaks it down in parts. -
_parseUri() public
Parses the given URI and breaks it down into pieces as an indexed array with elements such as 'scheme', 'port', 'query'.
-
_tokenEscapeChars() public
Gets escape chars according to RFC 2616 (HTTP 1.1 specs). -
_unescapeToken() public
Unescapes a given $token according to RFC 2616 (HTTP 1.1 specs) -
buildCookies() public
Builds cookie headers for a request. -
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. -
parseCookies() public
Parses cookies in response headers. -
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.
-
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( mixed $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
- mixed $config optional array()
- Configuration information, either a string url or an array of options.
Overrides
_buildHeader() public ¶
_buildHeader( array $header , $mode = 'standard' )
Builds the header.
Parameters
- array $header
- Header to build
- $mode optional 'standard'
Returns
Header built from array
_buildRequestLine() public ¶
_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
_buildUri() public ¶
_buildUri( mixed $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
- mixed $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 formated according to $uriTemplate, or false on failure
_configUri() public ¶
_configUri( mixed $uri = null )
Parses and sets the specified URI into current request configuration.
Parameters
- mixed $uri optional null
- URI, See HttpSocket::_parseUri()
Returns
Current configuration settings
_decodeBody() public ¶
_decodeBody( string $body , mixed $encoding = 'chunked' )
Generic function to decode a $body with a given $encoding. Returns either an array with the keys 'body' and 'header' or false on failure.
Parameters
- string $body
- A string continaing the body to decode.
- mixed $encoding optional 'chunked'
- Can be false in case no encoding is being used, or a string representing the encoding.
Returns
Array of response headers and body or false.
_decodeChunkedBody() public ¶
_decodeChunkedBody( string $body )
Decodes a chunked message $body and returns either an array with the keys 'body' and 'header' or false as a result.
Parameters
- string $body
- A string continaing the chunked body to decode.
Returns
Array of response headers and body or false.
_escapeToken() public ¶
_escapeToken( string $token , $chars = null )
Escapes a given $token according to RFC 2616 (HTTP 1.1 specs)
Parameters
- string $token
- Token to escape
- $chars optional null
Returns
Escaped token
_httpSerialize() public ¶
_httpSerialize( array $data = array() )
Serializes an array for transport.
Parameters
- array $data optional array()
- Data to serialize
Returns
Serialized variable
_parseHeader() public ¶
_parseHeader( array $header )
Parses an array based header.
Parameters
- array $header
- Header as an indexed array (field => value)
Returns
Parsed header
_parseQuery() public ¶
_parseQuery( mixed $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 menas 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
- mixed $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.
_parseResponse() public ¶
_parseResponse( string $message )
Parses the given message and breaks it down in parts.
Parameters
- string $message
- Message to parse
Returns
Parsed message (with indexed elements such as raw, status, header, body)
_parseUri() public ¶
_parseUri( string $uri = null , mixed $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 $uri optional null
- URI to parse
- mixed $base optional array()
- If true use default URI config, otherwise indexed array to set 'scheme', 'host', 'port', etc.
Returns
Parsed URI
_tokenEscapeChars() public ¶
_tokenEscapeChars( boolean $hex = true , $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
- $chars optional null
Returns
Escape chars
_unescapeToken() public ¶
_unescapeToken( string $token , $chars = null )
Unescapes a given $token according to RFC 2616 (HTTP 1.1 specs)
Parameters
- string $token
- Token to unescape
- $chars optional null
Returns
Unescaped token
buildCookies() public ¶
buildCookies( array $cookies )
Builds cookie headers for a request.
Parameters
- array $cookies
- Array of cookies to send with the request.
Returns
Cookie header string to be sent with the request.
delete() public ¶
delete( mixed $uri = null , array $data = array() , array $request = array() )
Issues a DELETE request to the specified URI, query, and request.
Parameters
- mixed $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( mixed $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
- mixed $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.
parseCookies() public ¶
parseCookies( array $header )
Parses cookies in response headers.
Parameters
- array $header
- Header array containing one ore more 'Set-Cookie' headers.
Returns
Either false on no cookies, or an array of cookies received.
post() public ¶
post( mixed $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
- mixed $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( mixed $uri = null , array $data = array() , array $request = array() )
Issues a PUT request to the specified URI, query, and request.
Parameters
- mixed $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( mixed $request = array() )
Issue the specified request. HttpSocket::get() and HttpSocket::post() wrap this method and provide a more granular interface.
Parameters
- mixed $request optional array()
- Either an URI string, or an array defining host/uri
Returns
false on error, request body on success
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
url() public ¶
url( mixed $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->configUri('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
- mixed $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
Either false on failure or a string containing the composed url.
Methods inherited from CakeSocket
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
disconnect() public ¶
disconnect( )
Disconnect the socket from the current connection.
Returns
Success
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
Methods inherited from Object
Object() public ¶
Object( )
A hack to support __construct() on PHP 4 Hint: descendant classes have no PHP4 class_name() constructors, so this constructor gets called first and calls the top-layer __construct() which (if present) should call parent::__construct()
Returns
__openPersistent() public ¶
__openPersistent( string $name , string $type = null )
Open the persistent class file for reading Used by Object::_persist()
Parameters
- string $name
- Name of persisted class
- string $type optional null
- Type of persistance (e.g: registry)
_persist() public ¶
_persist( string $name , string $return , $object , $type = null )
Checks for a persistent class file, if found file is opened and true returned If file is not found a file is created and false returned If used in other locations of the model you should choose a unique name for the persistent file There are many uses for this method, see manual for examples
Parameters
- string $name
- name of the class to persist
- string $return
- $object the object to persist
- $object
- $type optional null
Returns
Success
_savePersistent() public ¶
_savePersistent( string $name , object $object )
You should choose a unique name for the persistent file
There are many uses for this method, see manual for examples
Parameters
- string $name
- name used for object to cache
- object $object
- the object to persist
Returns
true on save, throws error if file can not be created
_set() public ¶
_set( array $properties = array() )
Allows setting of multiple properties of the object in a single line of code. Will only set properties that are part of a class declaration.
Parameters
- array $properties optional array()
- An associative array containing properties and corresponding values.
_stop() public ¶
_stop( $status = 0 )
Stop execution of the current script. Wraps exit() making testing easier.
Parameters
- $status optional 0
- http://php.net/exit for values
cakeError() public ¶
cakeError( string $method , array $messages = array() )
Used to report user friendly errors. If there is a file app/error.php or app/app_error.php this file will be loaded error.php is the AppError class it should extend ErrorHandler class.
Parameters
- string $method
- Method to be called in the error class (AppError or ErrorHandler classes)
- array $messages optional array()
- Message that is to be displayed by the error class
Returns
message
dispatchMethod() public ¶
dispatchMethod( string $method , array $params = array() )
Calls a method on this object with the given parameters. Provides an OO wrapper
for call_user_func_array
Parameters
- string $method
- Name of the method to call
- array $params optional array()
- Parameter list to use when calling $method
Returns
Returns the result of the method call
log() public ¶
log( string $msg , integer $type = LOG_ERROR )
Convience method to write a message to CakeLog. See CakeLog::write() for more information on writing to logs.
Parameters
- string $msg
- Log message
- integer $type optional LOG_ERROR
- Error type constant. Defined in app/config/core.php.
Returns
Success of log write
requestAction() public ¶
requestAction( mixed $url , array $extra = array() )
Calls a controller's method from any location. Can be used to connect controllers together or tie plugins into a main application. requestAction can be used to return rendered views or fetch the return value from controller actions.
Parameters
- mixed $url
- String or array-based url.
- array $extra optional array()
- if array includes the key "return" it sets the AutoRender to true.
Returns
Boolean true or false on success/failure, or contents of rendered action if 'return' is set in $extra.
toString() public ¶
toString( )
Object-to-string conversion. Each class can override this method as necessary.
Returns
The name of this class
Properties detail
$config ¶
Default configuration settings for the HttpSocket
array( 'persistent' => false, 'host' => 'localhost', 'protocol' => 'tcp', 'port' => 80, 'timeout' => 30, 'request' => array( 'uri' => array( 'scheme' => 'http', 'host' => 'localhost', 'port' => 80 ), 'auth' => array( 'method' => 'Basic', 'user' => null, 'pass' => null ), '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 ¶
The default values to use for a request
array( 'method' => 'GET', 'uri' => array( 'scheme' => 'http', 'host' => null, 'port' => 80, 'user' => null, 'pass' => null, 'path' => null, 'query' => null, 'fragment' => null ), 'auth' => array( 'method' => 'Basic', 'user' => null, 'pass' => null ), 'version' => '1.1', 'body' => '', 'line' => null, 'header' => array( 'Connection' => 'close', 'User-Agent' => 'CakePHP' ), 'raw' => null, 'cookies' => array() )
$response ¶
The default structure for storing the response
array( 'raw' => array( 'status-line' => null, 'header' => null, 'body' => null, 'response' => null ), 'status' => array( 'http-version' => null, 'code' => null, 'reason-phrase' => null ), 'header' => array(), 'body' => '', 'cookies' => array() )