8 * This source file is subject to the new BSD license that is bundled
9 * with this package in the file LICENSE.txt.
10 * It is also available through the world-wide-web at this URL:
11 * http://framework.zend.com/license/new-bsd
12 * If you did not receive a copy of the license and are unable to
13 * obtain it through the world-wide-web, please send an email
14 * to license@zend.com so we can send you a copy immediately.
20 * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
21 * @license http://framework.zend.com/license/new-bsd New BSD License
27 require_once 'Zend/Loader.php';
33 require_once 'Zend/Uri.php';
37 * @see Zend_Http_Client_Adapter_Interface
39 require_once 'Zend/Http/Client/Adapter/Interface.php';
43 * @see Zend_Http_Response
45 require_once 'Zend/Http/Response.php';
48 * @see Zend_Http_Response_Stream
50 require_once 'Zend/Http/Response/Stream.php';
53 * Zend_Http_Client is an implemetation of an HTTP client in PHP. The client
54 * supports basic features like sending different HTTP requests and handling
55 * redirections, as well as more advanced features like proxy settings, HTTP
56 * authentication and cookie persistance (using a Zend_Http_CookieJar object)
58 * @todo Implement proxy settings
62 * @throws Zend_Http_Client_Exception
63 * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
64 * @license http://framework.zend.com/license/new-bsd New BSD License
66 class Zend_Http_Client
69 * HTTP request methods
75 const DELETE = 'DELETE';
76 const TRACE = 'TRACE';
77 const OPTIONS = 'OPTIONS';
78 const CONNECT = 'CONNECT';
79 const MERGE = 'MERGE';
82 * Supported HTTP Authentication methods
84 const AUTH_BASIC = 'basic';
85 //const AUTH_DIGEST = 'digest'; <-- not implemented yet
88 * HTTP protocol versions
96 const CONTENT_TYPE = 'Content-Type';
97 const CONTENT_LENGTH = 'Content-Length';
100 * POST data encoding methods
102 const ENC_URLENCODED = 'application/x-www-form-urlencoded';
103 const ENC_FORMDATA = 'multipart/form-data';
106 * Configuration array, set using the constructor or using ::setConfig()
110 protected $config = array(
112 'strictredirects' => false,
113 'useragent' => 'Zend_Http_Client',
115 'adapter' => 'Zend_Http_Client_Adapter_Socket',
116 'httpversion' => self::HTTP_1,
117 'keepalive' => false,
118 'storeresponse' => true,
120 'output_stream' => false,
121 'encodecookies' => true,
125 * The adapter used to preform the actual connection to the server
127 * @var Zend_Http_Client_Adapter_Interface
129 protected $adapter = null;
136 protected $uri = null;
139 * Associative array of request headers
143 protected $headers = array();
146 * HTTP request method
150 protected $method = self::GET;
153 * Associative array of GET parameters
157 protected $paramsGet = array();
160 * Assiciative array of POST parameters
164 protected $paramsPost = array();
167 * Request body content type (for POST requests)
171 protected $enctype = null;
174 * The raw post data to send. Could be set by setRawData($data, $enctype).
178 protected $raw_post_data = null;
181 * HTTP Authentication settings
183 * Expected to be an associative array with this structure:
184 * $this->auth = array('user' => 'username', 'password' => 'password', 'type' => 'basic')
185 * Where 'type' should be one of the supported authentication types (see the AUTH_*
186 * constants), for example 'basic' or 'digest'.
188 * If null, no authentication will be used.
195 * File upload arrays (used in POST requests)
197 * An associative array, where each element is of the format:
198 * 'name' => array('filename.txt', 'text/plain', 'This is the actual file contents')
202 protected $files = array();
205 * The client's cookie jar
207 * @var Zend_Http_CookieJar
209 protected $cookiejar = null;
212 * The last HTTP request sent by the client, as string
216 protected $last_request = null;
219 * The last HTTP response received by the client
221 * @var Zend_Http_Response
223 protected $last_response = null;
226 * Redirection counter
230 protected $redirectCounter = 0;
233 * Fileinfo magic database resource
235 * This varaiable is populated the first time _detectFileMimeType is called
236 * and is then reused on every call to this method
240 static protected $_fileInfoDb = null;
243 * Contructor method. Will create a new HTTP client. Accepts the target
244 * URL and optionally configuration array.
246 * @param Zend_Uri_Http|string $uri
247 * @param array $config Configuration key-value pairs.
249 public function __construct($uri = null, $config = null)
254 if ($config !== null) {
255 $this->setConfig($config);
260 * Set the URI for the next request
262 * @param Zend_Uri_Http|string $uri
263 * @return Zend_Http_Client
264 * @throws Zend_Http_Client_Exception
266 public function setUri($uri)
268 if (is_string($uri)) {
269 $uri = Zend_Uri::factory($uri);
272 if (!$uri instanceof Zend_Uri_Http) {
273 /** @see Zend_Http_Client_Exception */
274 require_once 'Zend/Http/Client/Exception.php';
275 throw new Zend_Http_Client_Exception('Passed parameter is not a valid HTTP URI.');
278 // Set auth if username and password has been specified in the uri
279 if ($uri->getUsername() && $uri->getPassword()) {
280 $this->setAuth($uri->getUsername(), $uri->getPassword());
283 // We have no ports, set the defaults
284 if (! $uri->getPort()) {
285 $uri->setPort(($uri->getScheme() == 'https' ? 443 : 80));
294 * Get the URI for the next request
296 * @param boolean $as_string If true, will return the URI as a string
297 * @return Zend_Uri_Http|string
299 public function getUri($as_string = false)
301 if ($as_string && $this->uri instanceof Zend_Uri_Http) {
302 return $this->uri->__toString();
309 * Set configuration parameters for this HTTP client
311 * @param Zend_Config | array $config
312 * @return Zend_Http_Client
313 * @throws Zend_Http_Client_Exception
315 public function setConfig($config = array())
317 if ($config instanceof Zend_Config) {
318 $config = $config->toArray();
320 } elseif (! is_array($config)) {
321 /** @see Zend_Http_Client_Exception */
322 require_once 'Zend/Http/Client/Exception.php';
323 throw new Zend_Http_Client_Exception('Array or Zend_Config object expected, got ' . gettype($config));
326 foreach ($config as $k => $v) {
327 $this->config[strtolower($k)] = $v;
330 // Pass configuration options to the adapter if it exists
331 if ($this->adapter instanceof Zend_Http_Client_Adapter_Interface) {
332 $this->adapter->setConfig($config);
339 * Set the next request's method
341 * Validated the passed method and sets it. If we have files set for
342 * POST requests, and the new method is not POST, the files are silently
345 * @param string $method
346 * @return Zend_Http_Client
347 * @throws Zend_Http_Client_Exception
349 public function setMethod($method = self::GET)
351 if (! preg_match('/^[^\x00-\x1f\x7f-\xff\(\)<>@,;:\\\\"\/\[\]\?={}\s]+$/', $method)) {
352 /** @see Zend_Http_Client_Exception */
353 require_once 'Zend/Http/Client/Exception.php';
354 throw new Zend_Http_Client_Exception("'{$method}' is not a valid HTTP request method.");
357 if ($method == self::POST && $this->enctype === null) {
358 $this->setEncType(self::ENC_URLENCODED);
361 $this->method = $method;
367 * Set one or more request headers
369 * This function can be used in several ways to set the client's request
371 * 1. By providing two parameters: $name as the header to set (eg. 'Host')
372 * and $value as it's value (eg. 'www.example.com').
373 * 2. By providing a single header string as the only parameter
374 * eg. 'Host: www.example.com'
375 * 3. By providing an array of headers as the first parameter
376 * eg. array('host' => 'www.example.com', 'x-foo: bar'). In This case
377 * the function will call itself recursively for each array item.
379 * @param string|array $name Header name, full header string ('Header: value')
380 * or an array of headers
381 * @param mixed $value Header value or null
382 * @return Zend_Http_Client
383 * @throws Zend_Http_Client_Exception
385 public function setHeaders($name, $value = null)
387 // If we got an array, go recusive!
388 if (is_array($name)) {
389 foreach ($name as $k => $v) {
391 $this->setHeaders($k, $v);
393 $this->setHeaders($v, null);
397 // Check if $name needs to be split
398 if ($value === null && (strpos($name, ':') > 0)) {
399 list($name, $value) = explode(':', $name, 2);
402 // Make sure the name is valid if we are in strict mode
403 if ($this->config['strict'] && (! preg_match('/^[a-zA-Z0-9-]+$/', $name))) {
404 /** @see Zend_Http_Client_Exception */
405 require_once 'Zend/Http/Client/Exception.php';
406 throw new Zend_Http_Client_Exception("{$name} is not a valid HTTP header name");
409 $normalized_name = strtolower($name);
411 // If $value is null or false, unset the header
412 if ($value === null || $value === false) {
413 unset($this->headers[$normalized_name]);
415 // Else, set the header
417 // Header names are stored lowercase internally.
418 if (is_string($value)) {
419 $value = trim($value);
421 $this->headers[$normalized_name] = array($name, $value);
429 * Get the value of a specific header
431 * Note that if the header has more than one value, an array
435 * @return string|array|null The header value or null if it is not set
437 public function getHeader($key)
439 $key = strtolower($key);
440 if (isset($this->headers[$key])) {
441 return $this->headers[$key][1];
448 * Set a GET parameter for the request. Wrapper around _setParameter
450 * @param string|array $name
451 * @param string $value
452 * @return Zend_Http_Client
454 public function setParameterGet($name, $value = null)
456 if (is_array($name)) {
457 foreach ($name as $k => $v)
458 $this->_setParameter('GET', $k, $v);
460 $this->_setParameter('GET', $name, $value);
467 * Set a POST parameter for the request. Wrapper around _setParameter
469 * @param string|array $name
470 * @param string $value
471 * @return Zend_Http_Client
473 public function setParameterPost($name, $value = null)
475 if (is_array($name)) {
476 foreach ($name as $k => $v)
477 $this->_setParameter('POST', $k, $v);
479 $this->_setParameter('POST', $name, $value);
486 * Set a GET or POST parameter - used by SetParameterGet and SetParameterPost
488 * @param string $type GET or POST
489 * @param string $name
490 * @param string $value
493 protected function _setParameter($type, $name, $value)
496 $type = strtolower($type);
499 $parray = &$this->paramsGet;
502 $parray = &$this->paramsPost;
506 if ($value === null) {
507 if (isset($parray[$name])) unset($parray[$name]);
509 $parray[$name] = $value;
514 * Get the number of redirections done on the last request
518 public function getRedirectionsCount()
520 return $this->redirectCounter;
524 * Set HTTP authentication parameters
526 * $type should be one of the supported types - see the self::AUTH_*
529 * To enable authentication:
531 * $this->setAuth('shahar', 'secret', Zend_Http_Client::AUTH_BASIC);
534 * To disable authentication:
536 * $this->setAuth(false);
539 * @see http://www.faqs.org/rfcs/rfc2617.html
540 * @param string|false $user User name or false disable authentication
541 * @param string $password Password
542 * @param string $type Authentication type
543 * @return Zend_Http_Client
544 * @throws Zend_Http_Client_Exception
546 public function setAuth($user, $password = '', $type = self::AUTH_BASIC)
548 // If we got false or null, disable authentication
549 if ($user === false || $user === null) {
552 // Clear the auth information in the uri instance as well
553 if ($this->uri instanceof Zend_Uri_Http) {
554 $this->getUri()->setUsername('');
555 $this->getUri()->setPassword('');
557 // Else, set up authentication
559 // Check we got a proper authentication type
560 if (! defined('self::AUTH_' . strtoupper($type))) {
561 /** @see Zend_Http_Client_Exception */
562 require_once 'Zend/Http/Client/Exception.php';
563 throw new Zend_Http_Client_Exception("Invalid or not supported authentication type: '$type'");
567 'user' => (string) $user,
568 'password' => (string) $password,
577 * Set the HTTP client's cookie jar.
579 * A cookie jar is an object that holds and maintains cookies across HTTP requests
582 * @param Zend_Http_CookieJar|boolean $cookiejar Existing cookiejar object, true to create a new one, false to disable
583 * @return Zend_Http_Client
584 * @throws Zend_Http_Client_Exception
586 public function setCookieJar($cookiejar = true)
588 Zend_Loader::loadClass('Zend_Http_CookieJar');
590 if ($cookiejar instanceof Zend_Http_CookieJar) {
591 $this->cookiejar = $cookiejar;
592 } elseif ($cookiejar === true) {
593 $this->cookiejar = new Zend_Http_CookieJar();
594 } elseif (! $cookiejar) {
595 $this->cookiejar = null;
597 /** @see Zend_Http_Client_Exception */
598 require_once 'Zend/Http/Client/Exception.php';
599 throw new Zend_Http_Client_Exception('Invalid parameter type passed as CookieJar');
606 * Return the current cookie jar or null if none.
608 * @return Zend_Http_CookieJar|null
610 public function getCookieJar()
612 return $this->cookiejar;
616 * Add a cookie to the request. If the client has no Cookie Jar, the cookies
617 * will be added directly to the headers array as "Cookie" headers.
619 * @param Zend_Http_Cookie|string $cookie
620 * @param string|null $value If "cookie" is a string, this is the cookie value.
621 * @return Zend_Http_Client
622 * @throws Zend_Http_Client_Exception
624 public function setCookie($cookie, $value = null)
626 Zend_Loader::loadClass('Zend_Http_Cookie');
628 if (is_array($cookie)) {
629 foreach ($cookie as $c => $v) {
631 $this->setCookie($c, $v);
633 $this->setCookie($v);
640 if ($value !== null && $this->config['encodecookies']) {
641 $value = urlencode($value);
644 if (isset($this->cookiejar)) {
645 if ($cookie instanceof Zend_Http_Cookie) {
646 $this->cookiejar->addCookie($cookie);
647 } elseif (is_string($cookie) && $value !== null) {
648 $cookie = Zend_Http_Cookie::fromString("{$cookie}={$value}",
650 $this->config['encodecookies']);
651 $this->cookiejar->addCookie($cookie);
654 if ($cookie instanceof Zend_Http_Cookie) {
655 $name = $cookie->getName();
656 $value = $cookie->getValue();
660 if (preg_match("/[=,; \t\r\n\013\014]/", $cookie)) {
661 /** @see Zend_Http_Client_Exception */
662 require_once 'Zend/Http/Client/Exception.php';
663 throw new Zend_Http_Client_Exception("Cookie name cannot contain these characters: =,; \t\r\n\013\014 ({$cookie})");
666 $value = addslashes($value);
668 if (! isset($this->headers['cookie'])) {
669 $this->headers['cookie'] = array('Cookie', '');
671 $this->headers['cookie'][1] .= $cookie . '=' . $value . '; ';
678 * Set a file to upload (using a POST request)
680 * Can be used in two ways:
682 * 1. $data is null (default): $filename is treated as the name if a local file which
683 * will be read and sent. Will try to guess the content type using mime_content_type().
684 * 2. $data is set - $filename is sent as the file name, but $data is sent as the file
685 * contents and no file is read from the file system. In this case, you need to
686 * manually set the Content-Type ($ctype) or it will default to
687 * application/octet-stream.
689 * @param string $filename Name of file to upload, or name to save as
690 * @param string $formname Name of form element to send as
691 * @param string $data Data to send (if null, $filename is read and sent)
692 * @param string $ctype Content type to use (if $data is set and $ctype is
693 * null, will be application/octet-stream)
694 * @return Zend_Http_Client
695 * @throws Zend_Http_Client_Exception
697 public function setFileUpload($filename, $formname, $data = null, $ctype = null)
699 if ($data === null) {
700 if (($data = @file_get_contents($filename)) === false) {
701 /** @see Zend_Http_Client_Exception */
702 require_once 'Zend/Http/Client/Exception.php';
703 throw new Zend_Http_Client_Exception("Unable to read file '{$filename}' for upload");
707 $ctype = $this->_detectFileMimeType($filename);
711 // Force enctype to multipart/form-data
712 $this->setEncType(self::ENC_FORMDATA);
714 $this->files[] = array(
715 'formname' => $formname,
716 'filename' => basename($filename),
725 * Set the encoding type for POST data
727 * @param string $enctype
728 * @return Zend_Http_Client
730 public function setEncType($enctype = self::ENC_URLENCODED)
732 $this->enctype = $enctype;
738 * Set the raw (already encoded) POST data.
740 * This function is here for two reasons:
741 * 1. For advanced user who would like to set their own data, already encoded
742 * 2. For backwards compatibilty: If someone uses the old post($data) method.
743 * this method will be used to set the encoded data.
745 * $data can also be stream (such as file) from which the data will be read.
747 * @param string|resource $data
748 * @param string $enctype
749 * @return Zend_Http_Client
751 public function setRawData($data, $enctype = null)
753 $this->raw_post_data = $data;
754 $this->setEncType($enctype);
755 if (is_resource($data)) {
756 // We've got stream data
757 $stat = @fstat($data);
759 $this->setHeaders(self::CONTENT_LENGTH, $stat['size']);
766 * Clear all GET and POST parameters
768 * Should be used to reset the request parameters if the client is
769 * used for several concurrent requests.
771 * clearAll parameter controls if we clean just parameters or also
774 * @param bool $clearAll Should all data be cleared?
775 * @return Zend_Http_Client
777 public function resetParameters($clearAll = false)
779 // Reset parameter data
780 $this->paramsGet = array();
781 $this->paramsPost = array();
782 $this->files = array();
783 $this->raw_post_data = null;
786 $this->headers = array();
787 $this->last_request = null;
788 $this->last_response = null;
790 // Clear outdated headers
791 if (isset($this->headers[strtolower(self::CONTENT_TYPE)])) {
792 unset($this->headers[strtolower(self::CONTENT_TYPE)]);
794 if (isset($this->headers[strtolower(self::CONTENT_LENGTH)])) {
795 unset($this->headers[strtolower(self::CONTENT_LENGTH)]);
803 * Get the last HTTP request as string
807 public function getLastRequest()
809 return $this->last_request;
813 * Get the last HTTP response received by this client
815 * If $config['storeresponse'] is set to false, or no response was
816 * stored yet, will return null
818 * @return Zend_Http_Response or null if none
820 public function getLastResponse()
822 return $this->last_response;
826 * Load the connection adapter
828 * While this method is not called more than one for a client, it is
829 * seperated from ->request() to preserve logic and readability
831 * @param Zend_Http_Client_Adapter_Interface|string $adapter
833 * @throws Zend_Http_Client_Exception
835 public function setAdapter($adapter)
837 if (is_string($adapter)) {
839 Zend_Loader::loadClass($adapter);
840 } catch (Zend_Exception $e) {
841 /** @see Zend_Http_Client_Exception */
842 require_once 'Zend/Http/Client/Exception.php';
843 throw new Zend_Http_Client_Exception("Unable to load adapter '$adapter': {$e->getMessage()}", 0, $e);
846 $adapter = new $adapter;
849 if (! $adapter instanceof Zend_Http_Client_Adapter_Interface) {
850 /** @see Zend_Http_Client_Exception */
851 require_once 'Zend/Http/Client/Exception.php';
852 throw new Zend_Http_Client_Exception('Passed adapter is not a HTTP connection adapter');
855 $this->adapter = $adapter;
856 $config = $this->config;
857 unset($config['adapter']);
858 $this->adapter->setConfig($config);
862 * Load the connection adapter
864 * @return Zend_Http_Client_Adapter_Interface $adapter
866 public function getAdapter()
868 return $this->adapter;
872 * Set streaming for received data
874 * @param string|boolean $streamfile Stream file, true for temp file, false/null for no streaming
875 * @return Zend_Http_Client
877 public function setStream($streamfile = true)
879 $this->setConfig(array("output_stream" => $streamfile));
884 * Get status of streaming for received data
885 * @return boolean|string
887 public function getStream()
889 return $this->config["output_stream"];
893 * Create temporary stream
897 protected function _openTempStream()
899 $this->_stream_name = $this->config['output_stream'];
900 if(!is_string($this->_stream_name)) {
901 // If name is not given, create temp name
902 $this->_stream_name = tempnam(isset($this->config['stream_tmp_dir'])?$this->config['stream_tmp_dir']:sys_get_temp_dir(),
906 if (false === ($fp = @fopen($this->_stream_name, "w+b"))) {
907 if ($this->adapter instanceof Zend_Http_Client_Adapter_Interface) {
908 $this->adapter->close();
910 require_once 'Zend/Http/Client/Exception.php';
911 throw new Zend_Http_Client_Exception("Could not open temp file {$this->_stream_name}");
918 * Send the HTTP request and return an HTTP response object
920 * @param string $method
921 * @return Zend_Http_Response
922 * @throws Zend_Http_Client_Exception
924 public function request($method = null)
926 if (! $this->uri instanceof Zend_Uri_Http) {
927 /** @see Zend_Http_Client_Exception */
928 require_once 'Zend/Http/Client/Exception.php';
929 throw new Zend_Http_Client_Exception('No valid URI has been passed to the client');
933 $this->setMethod($method);
935 $this->redirectCounter = 0;
938 // Make sure the adapter is loaded
939 if ($this->adapter == null) {
940 $this->setAdapter($this->config['adapter']);
943 // Send the first request. If redirected, continue.
945 // Clone the URI and add the additional GET parameters to it
946 $uri = clone $this->uri;
947 if (! empty($this->paramsGet)) {
948 $query = $uri->getQuery();
949 if (! empty($query)) {
952 $query .= http_build_query($this->paramsGet, null, '&');
954 $uri->setQuery($query);
957 $body = $this->_prepareBody();
958 $headers = $this->_prepareHeaders();
960 // check that adapter supports streaming before using it
961 if(is_resource($body) && !($this->adapter instanceof Zend_Http_Client_Adapter_Stream)) {
962 /** @see Zend_Http_Client_Exception */
963 require_once 'Zend/Http/Client/Exception.php';
964 throw new Zend_Http_Client_Exception('Adapter does not support streaming');
967 // Open the connection, send the request and read the response
968 $this->adapter->connect($uri->getHost(), $uri->getPort(),
969 ($uri->getScheme() == 'https' ? true : false));
971 if($this->config['output_stream']) {
972 if($this->adapter instanceof Zend_Http_Client_Adapter_Stream) {
973 $stream = $this->_openTempStream();
974 $this->adapter->setOutputStream($stream);
976 /** @see Zend_Http_Client_Exception */
977 require_once 'Zend/Http/Client/Exception.php';
978 throw new Zend_Http_Client_Exception('Adapter does not support streaming');
982 $this->last_request = $this->adapter->write($this->method,
983 $uri, $this->config['httpversion'], $headers, $body);
985 $response = $this->adapter->read();
987 /** @see Zend_Http_Client_Exception */
988 require_once 'Zend/Http/Client/Exception.php';
989 throw new Zend_Http_Client_Exception('Unable to read response, or response is empty');
992 if($this->config['output_stream']) {
994 // cleanup the adapter
995 $this->adapter->setOutputStream(null);
996 $response = Zend_Http_Response_Stream::fromStream($response, $stream);
997 $response->setStreamName($this->_stream_name);
998 if(!is_string($this->config['output_stream'])) {
999 // we used temp name, will need to clean up
1000 $response->setCleanup(true);
1003 $response = Zend_Http_Response::fromString($response);
1006 if ($this->config['storeresponse']) {
1007 $this->last_response = $response;
1010 // Load cookies into cookie jar
1011 if (isset($this->cookiejar)) {
1012 $this->cookiejar->addCookiesFromResponse($response, $uri);
1015 // If we got redirected, look for the Location header
1016 if ($response->isRedirect() && ($location = $response->getHeader('location'))) {
1018 // Check whether we send the exact same request again, or drop the parameters
1019 // and send a GET request
1020 if ($response->getStatus() == 303 ||
1021 ((! $this->config['strictredirects']) && ($response->getStatus() == 302 ||
1022 $response->getStatus() == 301))) {
1024 $this->resetParameters();
1025 $this->setMethod(self::GET);
1028 // If we got a well formed absolute URI
1029 if (Zend_Uri_Http::check($location)) {
1030 $this->setHeaders('host', null);
1031 $this->setUri($location);
1035 // Split into path and query and set the query
1036 if (strpos($location, '?') !== false) {
1037 list($location, $query) = explode('?', $location, 2);
1041 $this->uri->setQuery($query);
1043 // Else, if we got just an absolute path, set it
1044 if(strpos($location, '/') === 0) {
1045 $this->uri->setPath($location);
1047 // Else, assume we have a relative path
1049 // Get the current path directory, removing any trailing slashes
1050 $path = $this->uri->getPath();
1051 $path = rtrim(substr($path, 0, strrpos($path, '/')), "/");
1052 $this->uri->setPath($path . '/' . $location);
1055 ++$this->redirectCounter;
1058 // If we didn't get any location, stop redirecting
1062 } while ($this->redirectCounter < $this->config['maxredirects']);
1068 * Prepare the request headers
1072 protected function _prepareHeaders()
1076 // Set the host header
1077 if (! isset($this->headers['host'])) {
1078 $host = $this->uri->getHost();
1080 // If the port is not default, add it
1081 if (! (($this->uri->getScheme() == 'http' && $this->uri->getPort() == 80) ||
1082 ($this->uri->getScheme() == 'https' && $this->uri->getPort() == 443))) {
1083 $host .= ':' . $this->uri->getPort();
1086 $headers[] = "Host: {$host}";
1089 // Set the connection header
1090 if (! isset($this->headers['connection'])) {
1091 if (! $this->config['keepalive']) {
1092 $headers[] = "Connection: close";
1096 // Set the Accept-encoding header if not set - depending on whether
1097 // zlib is available or not.
1098 if (! isset($this->headers['accept-encoding'])) {
1099 if (function_exists('gzinflate')) {
1100 $headers[] = 'Accept-encoding: gzip, deflate';
1102 $headers[] = 'Accept-encoding: identity';
1106 // Set the Content-Type header
1107 if ($this->method == self::POST &&
1108 (! isset($this->headers[strtolower(self::CONTENT_TYPE)]) && isset($this->enctype))) {
1110 $headers[] = self::CONTENT_TYPE . ': ' . $this->enctype;
1113 // Set the user agent header
1114 if (! isset($this->headers['user-agent']) && isset($this->config['useragent'])) {
1115 $headers[] = "User-Agent: {$this->config['useragent']}";
1118 // Set HTTP authentication if needed
1119 if (is_array($this->auth)) {
1120 $auth = self::encodeAuthHeader($this->auth['user'], $this->auth['password'], $this->auth['type']);
1121 $headers[] = "Authorization: {$auth}";
1124 // Load cookies from cookie jar
1125 if (isset($this->cookiejar)) {
1126 $cookstr = $this->cookiejar->getMatchingCookies($this->uri,
1127 true, Zend_Http_CookieJar::COOKIE_STRING_CONCAT);
1130 $headers[] = "Cookie: {$cookstr}";
1134 // Add all other user defined headers
1135 foreach ($this->headers as $header) {
1136 list($name, $value) = $header;
1137 if (is_array($value)) {
1138 $value = implode(', ', $value);
1141 $headers[] = "$name: $value";
1148 * Prepare the request body (for POST and PUT requests)
1151 * @throws Zend_Http_Client_Exception
1153 protected function _prepareBody()
1155 // According to RFC2616, a TRACE request should not have a body.
1156 if ($this->method == self::TRACE) {
1160 if (isset($this->raw_post_data) && is_resource($this->raw_post_data)) {
1161 return $this->raw_post_data;
1163 // If mbstring overloads substr and strlen functions, we have to
1164 // override it's internal encoding
1165 if (function_exists('mb_internal_encoding') &&
1166 ((int) ini_get('mbstring.func_overload')) & 2) {
1168 $mbIntEnc = mb_internal_encoding();
1169 mb_internal_encoding('ASCII');
1172 // If we have raw_post_data set, just use it as the body.
1173 if (isset($this->raw_post_data)) {
1174 $this->setHeaders(self::CONTENT_LENGTH, strlen($this->raw_post_data));
1175 if (isset($mbIntEnc)) {
1176 mb_internal_encoding($mbIntEnc);
1179 return $this->raw_post_data;
1184 // If we have files to upload, force enctype to multipart/form-data
1185 if (count ($this->files) > 0) {
1186 $this->setEncType(self::ENC_FORMDATA);
1189 // If we have POST parameters or files, encode and add them to the body
1190 if (count($this->paramsPost) > 0 || count($this->files) > 0) {
1191 switch($this->enctype) {
1192 case self::ENC_FORMDATA:
1193 // Encode body as multipart/form-data
1194 $boundary = '---ZENDHTTPCLIENT-' . md5(microtime());
1195 $this->setHeaders(self::CONTENT_TYPE, self::ENC_FORMDATA . "; boundary={$boundary}");
1197 // Get POST parameters and encode them
1198 $params = self::_flattenParametersArray($this->paramsPost);
1199 foreach ($params as $pp) {
1200 $body .= self::encodeFormData($boundary, $pp[0], $pp[1]);
1204 foreach ($this->files as $file) {
1205 $fhead = array(self::CONTENT_TYPE => $file['ctype']);
1206 $body .= self::encodeFormData($boundary, $file['formname'], $file['data'], $file['filename'], $fhead);
1209 $body .= "--{$boundary}--\r\n";
1212 case self::ENC_URLENCODED:
1213 // Encode body as application/x-www-form-urlencoded
1214 $this->setHeaders(self::CONTENT_TYPE, self::ENC_URLENCODED);
1215 $body = http_build_query($this->paramsPost, '', '&');
1219 if (isset($mbIntEnc)) {
1220 mb_internal_encoding($mbIntEnc);
1223 /** @see Zend_Http_Client_Exception */
1224 require_once 'Zend/Http/Client/Exception.php';
1225 throw new Zend_Http_Client_Exception("Cannot handle content type '{$this->enctype}' automatically." .
1226 " Please use Zend_Http_Client::setRawData to send this kind of content.");
1231 // Set the Content-Length if we have a body or if request is POST/PUT
1232 if ($body || $this->method == self::POST || $this->method == self::PUT) {
1233 $this->setHeaders(self::CONTENT_LENGTH, strlen($body));
1236 if (isset($mbIntEnc)) {
1237 mb_internal_encoding($mbIntEnc);
1244 * Helper method that gets a possibly multi-level parameters array (get or
1245 * post) and flattens it.
1247 * The method returns an array of (key, value) pairs (because keys are not
1248 * necessarily unique. If one of the parameters in as array, it will also
1249 * add a [] suffix to the key.
1251 * This method is deprecated since Zend Framework 1.9 in favour of
1252 * self::_flattenParametersArray() and will be dropped in 2.0
1254 * @deprecated since 1.9
1256 * @param array $parray The parameters array
1257 * @param bool $urlencode Whether to urlencode the name and value
1260 protected function _getParametersRecursive($parray, $urlencode = false)
1262 // Issue a deprecated notice
1263 trigger_error("The " . __METHOD__ . " method is deprecated and will be dropped in 2.0.",
1266 if (! is_array($parray)) {
1269 $parameters = array();
1271 foreach ($parray as $name => $value) {
1273 $name = urlencode($name);
1276 // If $value is an array, iterate over it
1277 if (is_array($value)) {
1278 $name .= ($urlencode ? '%5B%5D' : '[]');
1279 foreach ($value as $subval) {
1281 $subval = urlencode($subval);
1283 $parameters[] = array($name, $subval);
1287 $value = urlencode($value);
1289 $parameters[] = array($name, $value);
1297 * Attempt to detect the MIME type of a file using available extensions
1299 * This method will try to detect the MIME type of a file. If the fileinfo
1300 * extension is available, it will be used. If not, the mime_magic
1301 * extension which is deprected but is still available in many PHP setups
1304 * If neither extension is available, the default application/octet-stream
1305 * MIME type will be returned
1307 * @param string $file File path
1308 * @return string MIME type
1310 protected function _detectFileMimeType($file)
1314 // First try with fileinfo functions
1315 if (function_exists('finfo_open')) {
1316 if (self::$_fileInfoDb === null) {
1317 self::$_fileInfoDb = @finfo_open(FILEINFO_MIME);
1320 if (self::$_fileInfoDb) {
1321 $type = finfo_file(self::$_fileInfoDb, $file);
1324 } elseif (function_exists('mime_content_type')) {
1325 $type = mime_content_type($file);
1328 // Fallback to the default application/octet-stream
1330 $type = 'application/octet-stream';
1337 * Encode data to a multipart/form-data part suitable for a POST request.
1339 * @param string $boundary
1340 * @param string $name
1341 * @param mixed $value
1342 * @param string $filename
1343 * @param array $headers Associative array of optional headers @example ("Content-Transfer-Encoding" => "binary")
1346 public static function encodeFormData($boundary, $name, $value, $filename = null, $headers = array()) {
1347 $ret = "--{$boundary}\r\n" .
1348 'Content-Disposition: form-data; name="' . $name .'"';
1351 $ret .= '; filename="' . $filename . '"';
1355 foreach ($headers as $hname => $hvalue) {
1356 $ret .= "{$hname}: {$hvalue}\r\n";
1360 $ret .= "{$value}\r\n";
1366 * Create a HTTP authentication "Authorization:" header according to the
1367 * specified user, password and authentication method.
1369 * @see http://www.faqs.org/rfcs/rfc2617.html
1370 * @param string $user
1371 * @param string $password
1372 * @param string $type
1374 * @throws Zend_Http_Client_Exception
1376 public static function encodeAuthHeader($user, $password, $type = self::AUTH_BASIC)
1381 case self::AUTH_BASIC:
1382 // In basic authentication, the user name cannot contain ":"
1383 if (strpos($user, ':') !== false) {
1384 /** @see Zend_Http_Client_Exception */
1385 require_once 'Zend/Http/Client/Exception.php';
1386 throw new Zend_Http_Client_Exception("The user name cannot contain ':' in 'Basic' HTTP authentication");
1389 $authHeader = 'Basic ' . base64_encode($user . ':' . $password);
1392 //case self::AUTH_DIGEST:
1394 * @todo Implement digest authentication
1399 /** @see Zend_Http_Client_Exception */
1400 require_once 'Zend/Http/Client/Exception.php';
1401 throw new Zend_Http_Client_Exception("Not a supported HTTP authentication type: '$type'");
1408 * Convert an array of parameters into a flat array of (key, value) pairs
1410 * Will flatten a potentially multi-dimentional array of parameters (such
1411 * as POST parameters) into a flat array of (key, value) paris. In case
1412 * of multi-dimentional arrays, square brackets ([]) will be added to the
1413 * key to indicate an array.
1417 * @param array $parray
1418 * @param string $prefix
1421 static protected function _flattenParametersArray($parray, $prefix = null)
1423 if (! is_array($parray)) {
1427 $parameters = array();
1429 foreach($parray as $name => $value) {
1431 // Calculate array key
1433 if (is_int($name)) {
1434 $key = $prefix . '[]';
1436 $key = $prefix . "[$name]";
1442 if (is_array($value)) {
1443 $parameters = array_merge($parameters, self::_flattenParametersArray($value, $key));
1446 $parameters[] = array($key, $value);