Source for file Client.php
Documentation is available at Client.php
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
* @package Microsoft_Http
* @version $Id: Client.php 19661 2009-12-15 18:03:07Z matthew $
* @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @see Microsoft_AutoLoader
require_once dirname(__FILE__ ) . '/../AutoLoader.php';
* Microsoft_Http_Client is an implemetation of an HTTP client in PHP. The client
* supports basic features like sending different HTTP requests and handling
* redirections, as well as more advanced features like proxy settings, HTTP
* authentication and cookie persistance (using a Microsoft_Http_CookieJar object)
* @todo Implement proxy settings
* @package Microsoft_Http
* @throws Microsoft_Http_Client_Exception
* @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
const OPTIONS = 'OPTIONS';
const CONNECT = 'CONNECT';
* Supported HTTP Authentication methods
const AUTH_BASIC = 'basic';
//const AUTH_DIGEST = 'digest'; <-- not implemented yet
const CONTENT_TYPE = 'Content-Type';
const CONTENT_LENGTH = 'Content-Length';
* POST data encoding methods
const ENC_URLENCODED = 'application/x-www-form-urlencoded';
const ENC_FORMDATA = 'multipart/form-data';
* Configuration array, set using the constructor or using ::setConfig()
'strictredirects' => false,
'useragent' => 'Microsoft_Http_Client',
'adapter' => 'Microsoft_Http_Client_Adapter_Socket',
'httpversion' => self::HTTP_1,
'output_stream' => false,
* The adapter used to preform the actual connection to the server
* @var Microsoft_Http_Client_Adapter_Interface
* @var Microsoft_Uri_Http
* Associative array of request headers
* Associative array of GET parameters
* Assiciative array of POST parameters
* Request body content type (for POST requests)
* The raw post data to send. Could be set by setRawData($data, $enctype).
* HTTP Authentication settings
* Expected to be an associative array with this structure:
* $this->auth = array('user' => 'username', 'password' => 'password', 'type' => 'basic')
* Where 'type' should be one of the supported authentication types (see the AUTH_*
* constants), for example 'basic' or 'digest'.
* If null, no authentication will be used.
* File upload arrays (used in POST requests)
* An associative array, where each element is of the format:
* 'name' => array('filename.txt', 'text/plain', 'This is the actual file contents')
* The client's cookie jar
* @var Microsoft_Http_CookieJar
* The last HTTP request sent by the client, as string
* The last HTTP response received by the client
* @var Microsoft_Http_Response
* Fileinfo magic database resource
* This varaiable is populated the first time _detectFileMimeType is called
* and is then reused on every call to this method
* Contructor method. Will create a new HTTP client. Accepts the target
* URL and optionally configuration array.
* @param Microsoft_Uri_Http|string$uri
* @param array $config Configuration key-value pairs.
public function __construct($uri = null, $config = null)
* Set the URI for the next request
* @param Microsoft_Uri_Http|string$uri
* @return Microsoft_Http_Client
* @throws Microsoft_Http_Client_Exception
/** @see Microsoft_Http_Client_Exception */
require_once 'Microsoft/Http/Client/Exception.php';
// Set auth if username and password has been specified in the uri
if ($uri->getUsername() && $uri->getPassword()) {
$this->setAuth($uri->getUsername(), $uri->getPassword());
// We have no ports, set the defaults
$uri->setPort(($uri->getScheme() == 'https' ? 443 : 80));
* Get the URI for the next request
* @param boolean $as_string If true, will return the URI as a string
* @return Microsoft_Uri_Http|string
public function getUri($as_string = false)
return $this->uri->__toString();
* Set configuration parameters for this HTTP client
* @param Microsoft_Config | array $config
* @return Microsoft_Http_Client
* @throws Microsoft_Http_Client_Exception
if ($config instanceof Microsoft_Config) {
$config = $config->toArray();
/** @see Microsoft_Http_Client_Exception */
require_once 'Microsoft/Http/Client/Exception.php';
foreach ($config as $k => $v) {
// Pass configuration options to the adapter if it exists
* Set the next request's method
* Validated the passed method and sets it. If we have files set for
* POST requests, and the new method is not POST, the files are silently
* @return Microsoft_Http_Client
* @throws Microsoft_Http_Client_Exception
public function setMethod($method = self::GET)
if (! preg_match('/^[^\x00-\x1f\x7f-\xff\(\)<>@,;:\\\\"\/\[\]\?={}\s]+$/', $method)) {
/** @see Microsoft_Http_Client_Exception */
require_once 'Microsoft/Http/Client/Exception.php';
if ($method == self::POST && $this->enctype === null) {
* Set one or more request headers
* This function can be used in several ways to set the client's request
* 1. By providing two parameters: $name as the header to set (eg. 'Host')
* and $value as it's value (eg. 'www.example.com').
* 2. By providing a single header string as the only parameter
* eg. 'Host: www.example.com'
* 3. By providing an array of headers as the first parameter
* eg. array('host' => 'www.example.com', 'x-foo: bar'). In This case
* the function will call itself recursively for each array item.
* @param string|array$name Header name, full header string ('Header: value')
* @param mixed $value Header value or null
* @return Microsoft_Http_Client
* @throws Microsoft_Http_Client_Exception
// If we got an array, go recusive!
foreach ($name as $k => $v) {
// Check if $name needs to be split
if ($value === null && (strpos($name, ':') > 0)) {
list ($name, $value) = explode(':', $name, 2);
// Make sure the name is valid if we are in strict mode
/** @see Microsoft_Http_Client_Exception */
require_once 'Microsoft/Http/Client/Exception.php';
// If $value is null or false, unset the header
if ($value === null || $value === false) {
unset ($this->headers[$normalized_name]);
// Header names are stored lowercase internally.
$this->headers[$normalized_name] = array($name, $value);
* Get the value of a specific header
* Note that if the header has more than one value, an array
* @return string|array|nullThe header value or null if it is not set
* Set a GET parameter for the request. Wrapper around _setParameter
* @param string|array$name
* @return Microsoft_Http_Client
foreach ($name as $k => $v)
* Set a POST parameter for the request. Wrapper around _setParameter
* @param string|array$name
* @return Microsoft_Http_Client
foreach ($name as $k => $v)
* Set a GET or POST parameter - used by SetParameterGet and SetParameterPost
* @param string $type GET or POST
if (isset ($parray[$name])) unset ($parray[$name]);
* Get the number of redirections done on the last request
* Set HTTP authentication parameters
* $type should be one of the supported types - see the self::AUTH_*
* To enable authentication:
* $this->setAuth('shahar', 'secret', Microsoft_Http_Client::AUTH_BASIC);
* To disable authentication:
* @see http://www.faqs.org/rfcs/rfc2617.html
* @param string|false$user User name or false disable authentication
* @param string $password Password
* @param string $type Authentication type
* @return Microsoft_Http_Client
* @throws Microsoft_Http_Client_Exception
public function setAuth($user, $password = '', $type = self::AUTH_BASIC)
// If we got false or null, disable authentication
if ($user === false || $user === null) {
// Clear the auth information in the uri instance as well
$this->getUri()->setUsername('');
$this->getUri()->setPassword('');
// Else, set up authentication
// Check we got a proper authentication type
/** @see Microsoft_Http_Client_Exception */
require_once 'Microsoft/Http/Client/Exception.php';
'user' => (string) $user,
'password' => (string) $password,
* Set the HTTP client's cookie jar.
* A cookie jar is an object that holds and maintains cookies across HTTP requests
* @param Microsoft_Http_CookieJar|boolean$cookiejar Existing cookiejar object, true to create a new one, false to disable
* @return Microsoft_Http_Client
* @throws Microsoft_Http_Client_Exception
require_once 'Microsoft/Http/CookieJar.php';
} elseif ($cookiejar === true) {
} elseif (! $cookiejar) {
/** @see Microsoft_Http_Client_Exception */
require_once 'Microsoft/Http/Client/Exception.php';
* Return the current cookie jar or null if none.
* @return Microsoft_Http_CookieJar|null
* Add a cookie to the request. If the client has no Cookie Jar, the cookies
* will be added directly to the headers array as "Cookie" headers.
* @param Microsoft_Http_Cookie|string$cookie
* @param string|null$value If "cookie" is a string, this is the cookie value.
* @return Microsoft_Http_Client
* @throws Microsoft_Http_Client_Exception
public function setCookie($cookie, $value = null)
require_once 'Microsoft/Http/Cookie.php';
foreach ($cookie as $c => $v) {
} elseif (is_string($cookie) && $value !== null) {
$name = $cookie->getName();
$value = $cookie->getValue();
if (preg_match("/[=,; \t\r\n\013\014]/", $cookie)) {
/** @see Microsoft_Http_Client_Exception */
require_once 'Microsoft/Http/Client/Exception.php';
if (! isset ($this->headers['cookie'])) {
$this->headers['cookie'] = array('Cookie', '');
$this->headers['cookie'][1] .= $cookie . '=' . $value . '; ';
* Set a file to upload (using a POST request)
* Can be used in two ways:
* 1. $data is null (default): $filename is treated as the name if a local file which
* will be read and sent. Will try to guess the content type using mime_content_type().
* 2. $data is set - $filename is sent as the file name, but $data is sent as the file
* contents and no file is read from the file system. In this case, you need to
* manually set the Content-Type ($ctype) or it will default to
* application/octet-stream.
* @param string $filename Name of file to upload, or name to save as
* @param string $formname Name of form element to send as
* @param string $data Data to send (if null, $filename is read and sent)
* @param string $ctype Content type to use (if $data is set and $ctype is
* null, will be application/octet-stream)
* @return Microsoft_Http_Client
* @throws Microsoft_Http_Client_Exception
public function setFileUpload($filename, $formname, $data = null, $ctype = null)
/** @see Microsoft_Http_Client_Exception */
require_once 'Microsoft/Http/Client/Exception.php';
// Force enctype to multipart/form-data
* Set the encoding type for POST data
* @return Microsoft_Http_Client
public function setEncType($enctype = self::ENC_URLENCODED)
* Set the raw (already encoded) POST data.
* This function is here for two reasons:
* 1. For advanced user who would like to set their own data, already encoded
* 2. For backwards compatibilty: If someone uses the old post($data) method.
* this method will be used to set the encoded data.
* $data can also be stream (such as file) from which the data will be read.
* @param string|resource$data
* @return Microsoft_Http_Client
public function setRawData($data, $enctype = null)
$this->setHeaders(self::CONTENT_LENGTH, $stat['size']);
* Clear all GET and POST parameters
* Should be used to reset the request parameters if the client is
* used for several concurrent requests.
* clearAll parameter controls if we clean just parameters or also
* @param bool $clearAll Should all data be cleared?
* @return Microsoft_Http_Client
// Clear outdated headers
* Get the last HTTP request as string
* Get the last HTTP response received by this client
* If $config['storeresponse'] is set to false, or no response was
* stored yet, will return null
* @return Microsoft_Http_Response or null if none
* Load the connection adapter
* While this method is not called more than one for a client, it is
* seperated from ->request() to preserve logic and readability
* @param Microsoft_Http_Client_Adapter_Interface|string$adapter
* @throws Microsoft_Http_Client_Exception
@require_once( str_replace('_', '/', $adapter) . '.php' );
/** @see Microsoft_Http_Client_Exception */
require_once 'Microsoft/Http/Client/Exception.php';
unset ($config['adapter']);
* Load the connection adapter
* @return Microsoft_Http_Client_Adapter_Interface $adapter
* Set streaming for received data
* @param string|boolean$streamfile Stream file, true for temp file, false/null for no streaming
* @return Microsoft_Http_Client
public function setStream($streamfile = true)
$this->setConfig(array("output_stream" => $streamfile));
* Get status of streaming for received data
return $this->config["output_stream"];
* Create temporary stream
$this->_stream_name = $this->config['output_stream'];
// If name is not given, create temp name
'Microsoft_Http_Client');
$fp = fopen($this->_stream_name, "w+b");
require_once 'Microsoft/Http/Client/Exception.php';
* Send the HTTP request and return an HTTP response object
* @return Microsoft_Http_Response
* @throws Microsoft_Http_Client_Exception
public function request($method = null)
/** @see Microsoft_Http_Client_Exception */
require_once 'Microsoft/Http/Client/Exception.php';
// Make sure the adapter is loaded
// Send the first request. If redirected, continue.
// Clone the URI and add the additional GET parameters to it
$query = $uri->getQuery();
// check that adapter supports streaming before using it
/** @see Microsoft_Http_Client_Exception */
require_once 'Microsoft/Http/Client/Exception.php';
// Open the connection, send the request and read the response
($uri->getScheme() == 'https' ? true : false));
if($this->config['output_stream']) {
$this->adapter->setOutputStream($stream);
/** @see Microsoft_Http_Client_Exception */
require_once 'Microsoft/Http/Client/Exception.php';
$uri, $this->config['httpversion'], $headers, $body);
/** @see Microsoft_Http_Client_Exception */
require_once 'Microsoft/Http/Client/Exception.php';
if($this->config['output_stream']) {
$this->adapter->setOutputStream(null);
$response->setStreamName($this->_stream_name);
// we used temp name, will need to clean up
$response->setCleanup(true);
if ($this->config['storeresponse']) {
// Load cookies into cookie jar
// If we got redirected, look for the Location header
if ($response->isRedirect() && ($location = $response->getHeader('location'))) {
// Check whether we send the exact same request again, or drop the parameters
// and send a GET request
if ($response->getStatus() == 303 ||
((! $this->config['strictredirects']) && ($response->getStatus() == 302 ||
$response->getStatus() == 301))) {
// If we got a well formed absolute URI
// Split into path and query and set the query
if (strpos($location, '?') !== false) {
list ($location, $query) = explode('?', $location, 2);
$this->uri->setQuery($query);
// Else, if we got just an absolute path, set it
if(strpos($location, '/') === 0) {
$this->uri->setPath($location);
// Else, assume we have a relative path
// Get the current path directory, removing any trailing slashes
$path = $this->uri->getPath();
$this->uri->setPath($path . '/' . $location);
// If we didn't get any location, stop redirecting
* Prepare the request headers
if (! isset ($this->headers['host'])) {
$host = $this->uri->getHost();
// If the port is not default, add it
if (! (($this->uri->getScheme() == 'http' && $this->uri->getPort() == 80) ||
($this->uri->getScheme() == 'https' && $this->uri->getPort() == 443))) {
$host .= ':' . $this->uri->getPort();
$headers[] = "Host: {$host}";
// Set the connection header
if (! isset ($this->headers['connection'])) {
if (! $this->config['keepalive']) {
$headers[] = "Connection: close";
// Set the Accept-encoding header if not set - depending on whether
// zlib is available or not.
if (! isset ($this->headers['accept-encoding'])) {
$headers[] = 'Accept-encoding: gzip, deflate';
$headers[] = 'Accept-encoding: identity';
// Set the Content-Type header
if ($this->method == self::POST &&
$headers[] = self::CONTENT_TYPE . ': ' . $this->enctype;
// Set the user agent header
if (! isset ($this->headers['user-agent']) && isset ($this->config['useragent'])) {
$headers[] = "User-Agent: {$this->config['useragent']}";
// Set HTTP authentication if needed
$auth = self::encodeAuthHeader($this->auth['user'], $this->auth['password'], $this->auth['type']);
$headers[] = "Authorization: {$auth}";
// Load cookies from cookie jar
$headers[] = "Cookie: {$cookstr}";
// Add all other user defined headers
foreach ($this->headers as $header) {
list ($name, $value) = $header;
$headers[] = "$name: $value";
* Prepare the request body (for POST and PUT requests)
* @throws Microsoft_Http_Client_Exception
// According to RFC2616, a TRACE request should not have a body.
if ($this->method == self::TRACE) {
// If mbstring overloads substr and strlen functions, we have to
// override it's internal encoding
((int) ini_get('mbstring.func_overload')) & 2) {
// If we have raw_post_data set, just use it as the body.
// If we have files to upload, force enctype to multipart/form-data
// If we have POST parameters or files, encode and add them to the body
// Encode body as multipart/form-data
$this->setHeaders(self::CONTENT_TYPE, self::ENC_FORMDATA . "; boundary={$boundary}");
// Get POST parameters and encode them
$params = self::_flattenParametersArray($this->paramsPost);
foreach ($params as $pp) {
$body .= self::encodeFormData($boundary, $pp[0], $pp[1]);
foreach ($this->files as $file) {
$fhead = array(self::CONTENT_TYPE => $file['ctype']);
$body .= self::encodeFormData($boundary, $file['formname'], $file['data'], $file['filename'], $fhead);
$body .= "--{$boundary}--\r\n";
case self::ENC_URLENCODED:
// Encode body as application/x-www-form-urlencoded
$this->setHeaders(self::CONTENT_TYPE, self::ENC_URLENCODED);
/** @see Microsoft_Http_Client_Exception */
require_once 'Microsoft/Http/Client/Exception.php';
" Please use Microsoft_Http_Client::setRawData to send this kind of content.");
// Set the Content-Length if we have a body or if request is POST/PUT
if ($body || $this->method == self::POST || $this->method == self::PUT) {
$this->setHeaders(self::CONTENT_LENGTH, strlen($body));
mb_internal_encoding($mbIntEnc);
* Helper method that gets a possibly multi-level parameters array (get or
* The method returns an array of (key, value) pairs (because keys are not
* necessarily unique. If one of the parameters in as array, it will also
* add a [] suffix to the key.
* This method is deprecated since Zend Framework 1.9 in favour of
* self::_flattenParametersArray() and will be dropped in 2.0
* @param array $parray The parameters array
* @param bool $urlencode Whether to urlencode the name and value
protected function _getParametersRecursive($parray, $urlencode = false)
// Issue a deprecated notice
trigger_error("The " . __METHOD__ . " method is deprecated and will be dropped in 2.0.",
foreach ($parray as $name => $value) {
// If $value is an array, iterate over it
$name .= ($urlencode ? '%5B%5D' : '[]');
foreach ($value as $subval) {
$parameters[] = array($name, $subval);
$parameters[] = array($name, $value);
* Attempt to detect the MIME type of a file using available extensions
* This method will try to detect the MIME type of a file. If the fileinfo
* extension is available, it will be used. If not, the mime_magic
* extension which is deprected but is still available in many PHP setups
* If neither extension is available, the default application/octet-stream
* MIME type will be returned
* @param string $file File path
* @return string MIME type
// First try with fileinfo functions
if (self::$_fileInfoDb === null) {
self::$_fileInfoDb = @finfo_open(FILEINFO_MIME);
if (self::$_fileInfoDb) {
$type = finfo_file(self::$_fileInfoDb, $file);
} elseif (function_exists('mime_content_type')) {
$type = mime_content_type($file);
// Fallback to the default application/octet-stream
$type = 'application/octet-stream';
* Encode data to a multipart/form-data part suitable for a POST request.
* @param string $boundary
* @param string $filename
* @param array $headers Associative array of optional headers @example ("Content-Transfer-Encoding" => "binary")
public static function encodeFormData($boundary, $name, $value, $filename = null, $headers = array()) {
$ret = "--{ $boundary}\r\n " .
'Content-Disposition: form-data; name="' . $name .'"';
$ret .= '; filename="' . $filename . '"';
foreach ($headers as $hname => $hvalue) {
$ret .= "{$hname}: {$hvalue}\r\n";
* Create a HTTP authentication "Authorization:" header according to the
* specified user, password and authentication method.
* @see http://www.faqs.org/rfcs/rfc2617.html
* @param string $password
* @throws Microsoft_Http_Client_Exception
public static function encodeAuthHeader($user, $password, $type = self::AUTH_BASIC)
// In basic authentication, the user name cannot contain ":"
if (strpos($user, ':') !== false) {
/** @see Microsoft_Http_Client_Exception */
require_once 'Microsoft/Http/Client/Exception.php';
//case self::AUTH_DIGEST:
* @todo Implement digest authentication
/** @see Microsoft_Http_Client_Exception */
require_once 'Microsoft/Http/Client/Exception.php';
* Convert an array of parameters into a flat array of (key, value) pairs
* Will flatten a potentially multi-dimentional array of parameters (such
* as POST parameters) into a flat array of (key, value) paris. In case
* of multi-dimentional arrays, square brackets ([]) will be added to the
* key to indicate an array.
foreach($parray as $name => $value) {
$key = $prefix . "[$name]";
$parameters = array_merge($parameters, self::_flattenParametersArray($value, $key));
$parameters[] = array($key, $value);
|