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.
19 * @version $Id: Client.php 8064 2008-02-16 10:58:39Z thomas $
20 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
21 * @license http://framework.zend.com/license/new-bsd New BSD License
24 require_once 'external/Zend/Loader.php';
25 require_once 'external/Zend/Uri.php';
26 require_once 'external/Zend/Http/Client/Adapter/Interface.php';
27 require_once 'external/Zend/Http/Response.php';
30 * Zend_Http_Client is an implemetation of an HTTP client in PHP. The client
31 * supports basic features like sending different HTTP requests and handling
32 * redirections, as well as more advanced features like proxy settings, HTTP
33 * authentication and cookie persistance (using a Zend_Http_CookieJar object)
35 * @todo Implement proxy settings
39 * @throws Zend_Http_Client_Exception
40 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
41 * @license http://framework.zend.com/license/new-bsd New BSD License
43 class Zend_Http_Client
{
45 * HTTP request methods
51 const DELETE
= 'DELETE';
52 const TRACE
= 'TRACE';
53 const OPTIONS
= 'OPTIONS';
54 const CONNECT
= 'CONNECT';
57 * Supported HTTP Authentication methods
59 const AUTH_BASIC
= 'basic';
60 //const AUTH_DIGEST = 'digest'; <-- not implemented yet
64 * HTTP protocol versions
70 * POST data encoding methods
72 const ENC_URLENCODED
= 'application/x-www-form-urlencoded';
73 const ENC_FORMDATA
= 'multipart/form-data';
76 * Configuration array, set using the constructor or using ::setConfig()
80 protected $config = array('maxredirects' => 5, 'strictredirects' => false,
81 'useragent' => 'Zend_Http_Client', 'timeout' => 10,
82 'adapter' => 'Zend_Http_Client_Adapter_Socket', 'httpversion' => self
::HTTP_1
,
83 'keepalive' => false, 'storeresponse' => true, 'strict' => true);
86 * The adapter used to preform the actual connection to the server
88 * @var Zend_Http_Client_Adapter_Interface
90 protected $adapter = null;
100 * Associative array of request headers
104 protected $headers = array();
107 * HTTP request method
111 protected $method = self
::GET
;
114 * Associative array of GET parameters
118 protected $paramsGet = array();
121 * Assiciative array of POST parameters
125 protected $paramsPost = array();
128 * Request body content type (for POST requests)
132 protected $enctype = null;
135 * The raw post data to send. Could be set by setRawData($data, $enctype).
139 protected $raw_post_data = null;
142 * HTTP Authentication settings
144 * Expected to be an associative array with this structure:
145 * $this->auth = array('user' => 'username', 'password' => 'password', 'type' => 'basic')
146 * Where 'type' should be one of the supported authentication types (see the AUTH_*
147 * constants), for example 'basic' or 'digest'.
149 * If null, no authentication will be used.
156 * File upload arrays (used in POST requests)
158 * An associative array, where each element is of the format:
159 * 'name' => array('filename.txt', 'text/plain', 'This is the actual file contents')
163 protected $files = array();
166 * The client's cookie jar
168 * @var Zend_Http_CookieJar
170 protected $cookiejar = null;
173 * The last HTTP request sent by the client, as string
177 protected $last_request = null;
180 * The last HTTP response received by the client
182 * @var Zend_Http_Response
184 protected $last_response = null;
187 * Redirection counter
191 protected $redirectCounter = 0;
194 * Contructor method. Will create a new HTTP client. Accepts the target
195 * URL and optionally and array of headers.
197 * @param Zend_Uri_Http|string $uri
198 * @param array $headers Optional request headers to set
200 public function __construct($uri = null, $config = null) {
201 if ($uri !== null) $this->setUri($uri);
202 if ($config !== null) $this->setConfig($config);
206 * Set the URI for the next request
208 * @param Zend_Uri_Http|string $uri
209 * @return Zend_Http_Client
210 * @throws Zend_Http_Client_Exception
212 public function setUri($uri) {
213 if (is_string($uri)) {
214 $uri = Zend_Uri
::factory($uri);
217 if (! $uri instanceof Zend_Uri_Http
) {
218 require_once 'external/Zend/Http/Client/Exception.php';
219 throw new Zend_Http_Client_Exception('Passed parameter is not a valid HTTP URI.');
222 // We have no ports, set the defaults
223 if (! $uri->getPort()) {
224 $uri->setPort(($uri->getScheme() == 'https' ?
443 : 80));
233 * Get the URI for the next request
235 * @param boolean $as_string If true, will return the URI as a string
236 * @return Zend_Uri_Http|string
238 public function getUri($as_string = false) {
239 if ($as_string && $this->uri
instanceof Zend_Uri_Http
) {
240 return $this->uri
->__toString();
247 * Set configuration parameters for this HTTP client
249 * @param array $config
250 * @return Zend_Http_Client
252 public function setConfig($config = array()) {
253 if (! is_array($config)) {
254 require_once 'external/Zend/Http/Client/Exception.php';
255 throw new Zend_Http_Client_Exception('Expected array parameter, given ' . gettype($config));
258 foreach ($config as $k => $v)
259 $this->config
[strtolower($k)] = $v;
265 * Set the next request's method
267 * Validated the passed method and sets it. If we have files set for
268 * POST requests, and the new method is not POST, the files are silently
271 * @param string $method
272 * @return Zend_Http_Client
274 public function setMethod($method = self
::GET
) {
275 if (! preg_match('/^[A-Za-z_]+$/', $method)) {
276 require_once 'external/Zend/Http/Client/Exception.php';
277 throw new Zend_Http_Client_Exception("'{$method}' is not a valid HTTP request method.");
280 if ($method == self
::POST
&& $this->enctype
=== null) $this->setEncType(self
::ENC_URLENCODED
);
282 $this->method
= $method;
288 * Set one or more request headers
290 * This function can be used in several ways to set the client's request
292 * 1. By providing two parameters: $name as the header to set (eg. 'Host')
293 * and $value as it's value (eg. 'www.example.com').
294 * 2. By providing a single header string as the only parameter
295 * eg. 'Host: www.example.com'
296 * 3. By providing an array of headers as the first parameter
297 * eg. array('host' => 'www.example.com', 'x-foo: bar'). In This case
298 * the function will call itself recursively for each array item.
300 * @param string|array $name Header name, full header string ('Header: value')
301 * or an array of headers
302 * @param mixed $value Header value or null
303 * @return Zend_Http_Client
305 public function setHeaders($name, $value = null) {
306 // If we got an array, go recusive!
307 if (is_array($name)) {
308 foreach ($name as $k => $v) {
310 $this->setHeaders($k, $v);
312 $this->setHeaders($v, null);
316 // Check if $name needs to be split
317 if ($value === null && (strpos($name, ':') > 0)) list($name, $value) = explode(':', $name, 2);
319 // Make sure the name is valid if we are in strict mode
320 if ($this->config
['strict'] && (! preg_match('/^[a-zA-Z0-9-]+$/', $name))) {
321 require_once 'external/Zend/Http/Client/Exception.php';
322 throw new Zend_Http_Client_Exception("{$name} is not a valid HTTP header name");
325 $normalized_name = strtolower($name);
327 // If $value is null or false, unset the header
328 if ($value === null ||
$value === false) {
329 unset($this->headers
[$normalized_name]);
331 // Else, set the header
333 // Header names are storred lowercase internally.
334 if (is_string($value)) $value = trim($value);
335 $this->headers
[$normalized_name] = array($name, $value);
343 * Get the value of a specific header
345 * Note that if the header has more than one value, an array
348 * @param unknown_type $key
349 * @return string|array|null The header value or null if it is not set
351 public function getHeader($key) {
352 $key = strtolower($key);
353 if (isset($this->headers
[$key])) {
354 return $this->headers
[$key][1];
361 * Set a GET parameter for the request. Wrapper around _setParameter
363 * @param string|array $name
364 * @param string $value
365 * @return Zend_Http_Client
367 public function setParameterGet($name, $value = null) {
368 if (is_array($name)) {
369 foreach ($name as $k => $v)
370 $this->_setParameter('GET', $k, $v);
372 $this->_setParameter('GET', $name, $value);
379 * Set a POST parameter for the request. Wrapper around _setParameter
381 * @param string|array $name
382 * @param string $value
383 * @return Zend_Http_Client
385 public function setParameterPost($name, $value = null) {
386 if (is_array($name)) {
387 foreach ($name as $k => $v)
388 $this->_setParameter('POST', $k, $v);
390 $this->_setParameter('POST', $name, $value);
397 * Set a GET or POST parameter - used by SetParameterGet and SetParameterPost
399 * @param string $type GET or POST
400 * @param string $name
401 * @param string $value
403 protected function _setParameter($type, $name, $value) {
405 $type = strtolower($type);
408 $parray = &$this->paramsGet
;
411 $parray = &$this->paramsPost
;
415 if ($value === null) {
416 if (isset($parray[$name])) unset($parray[$name]);
418 $parray[$name] = $value;
423 * Get the number of redirections done on the last request
427 public function getRedirectionsCount() {
428 return $this->redirectCounter
;
432 * Set HTTP authentication parameters
434 * $type should be one of the supported types - see the self::AUTH_*
437 * To enable authentication:
439 * $this->setAuth('shahar', 'secret', Zend_Http_Client::AUTH_BASIC);
442 * To disable authentication:
444 * $this->setAuth(false);
447 * @see http://www.faqs.org/rfcs/rfc2617.html
448 * @param string|false $user User name or false disable authentication
449 * @param string $password Password
450 * @param string $type Authentication type
451 * @return Zend_Http_Client
453 public function setAuth($user, $password = '', $type = self
::AUTH_BASIC
) {
454 // If we got false or null, disable authentication
455 if ($user === false ||
$user === null) {
458 // Else, set up authentication
460 // Check we got a proper authentication type
461 if (! defined('self::AUTH_' . strtoupper($type))) {
462 require_once 'external/Zend/Http/Client/Exception.php';
463 throw new Zend_Http_Client_Exception("Invalid or not supported authentication type: '$type'");
466 $this->auth
= array('user' => (string)$user, 'password' => (string)$password,
474 * Set the HTTP client's cookie jar.
476 * A cookie jar is an object that holds and maintains cookies across HTTP requests
479 * @param Zend_Http_CookieJar|boolean $cookiejar Existing cookiejar object, true to create a new one, false to disable
480 * @return Zend_Http_Client
482 public function setCookieJar($cookiejar = true) {
483 if (! class_exists('Zend_Http_CookieJar')) require_once 'external/Zend/Http/CookieJar.php';
485 if ($cookiejar instanceof Zend_Http_CookieJar
) {
486 $this->cookiejar
= $cookiejar;
487 } elseif ($cookiejar === true) {
488 $this->cookiejar
= new Zend_Http_CookieJar();
489 } elseif (! $cookiejar) {
490 $this->cookiejar
= null;
492 require_once 'external/Zend/Http/Client/Exception.php';
493 throw new Zend_Http_Client_Exception('Invalid parameter type passed as CookieJar');
500 * Return the current cookie jar or null if none.
502 * @return Zend_Http_CookieJar|null
504 public function getCookieJar() {
505 return $this->cookiejar
;
509 * Add a cookie to the request. If the client has no Cookie Jar, the cookies
510 * will be added directly to the headers array as "Cookie" headers.
512 * @param Zend_Http_Cookie|string $cookie
513 * @param string|null $value If "cookie" is a string, this is the cookie value.
514 * @return Zend_Http_Client
516 public function setCookie($cookie, $value = null) {
517 if (! class_exists('Zend_Http_Cookie')) require_once 'external/Zend/Http/Cookie.php';
519 if (is_array($cookie)) {
520 foreach ($cookie as $c => $v) {
522 $this->setCookie($c, $v);
524 $this->setCookie($v);
531 if ($value !== null) $value = urlencode($value);
533 if (isset($this->cookiejar
)) {
534 if ($cookie instanceof Zend_Http_Cookie
) {
535 $this->cookiejar
->addCookie($cookie);
536 } elseif (is_string($cookie) && $value !== null) {
537 $cookie = Zend_Http_Cookie
::fromString("{$cookie}={$value}", $this->uri
);
538 $this->cookiejar
->addCookie($cookie);
541 if ($cookie instanceof Zend_Http_Cookie
) {
542 $name = $cookie->getName();
543 $value = $cookie->getValue();
547 if (preg_match("/[=,; \t\r\n\013\014]/", $cookie)) {
548 require_once 'external/Zend/Http/Client/Exception.php';
549 throw new Zend_Http_Client_Exception("Cookie name cannot contain these characters: =,; \t\r\n\013\014 ({$cookie})");
552 $value = addslashes($value);
554 if (! isset($this->headers
['cookie'])) $this->headers
['cookie'] = array('Cookie', '');
555 $this->headers
['cookie'][1] .= $cookie . '=' . $value . '; ';
562 * Set a file to upload (using a POST request)
564 * Can be used in two ways:
566 * 1. $data is null (default): $filename is treated as the name if a local file which
567 * will be read and sent. Will try to guess the content type using mime_content_type().
568 * 2. $data is set - $filename is sent as the file name, but $data is sent as the file
569 * contents and no file is read from the file system. In this case, you need to
570 * manually set the content-type ($ctype) or it will default to
571 * application/octet-stream.
573 * @param string $filename Name of file to upload, or name to save as
574 * @param string $formname Name of form element to send as
575 * @param string $data Data to send (if null, $filename is read and sent)
576 * @param string $ctype Content type to use (if $data is set and $ctype is
577 * null, will be application/octet-stream)
578 * @return Zend_Http_Client
580 public function setFileUpload($filename, $formname, $data = null, $ctype = null) {
581 if ($data === null) {
582 if (($data = @file_get_contents
($filename)) === false) {
583 require_once 'external/Zend/Http/Client/Exception.php';
584 throw new Zend_Http_Client_Exception("Unable to read file '{$filename}' for upload");
587 if (! $ctype && function_exists('mime_content_type')) $ctype = mime_content_type($filename);
590 // Force enctype to multipart/form-data
591 $this->setEncType(self
::ENC_FORMDATA
);
593 if ($ctype === null) $ctype = 'application/octet-stream';
594 $this->files
[$formname] = array(basename($filename), $ctype, $data);
600 * Set the encoding type for POST data
602 * @param string $enctype
603 * @return Zend_Http_Client
605 public function setEncType($enctype = self
::ENC_URLENCODED
) {
606 $this->enctype
= $enctype;
612 * Set the raw (already encoded) POST data.
614 * This function is here for two reasons:
615 * 1. For advanced user who would like to set their own data, already encoded
616 * 2. For backwards compatibilty: If someone uses the old post($data) method.
617 * this method will be used to set the encoded data.
619 * @param string $data
620 * @param string $enctype
621 * @return Zend_Http_Client
623 public function setRawData($data, $enctype = null) {
624 $this->raw_post_data
= $data;
625 $this->setEncType($enctype);
631 * Clear all GET and POST parameters
633 * Should be used to reset the request parameters if the client is
634 * used for several concurrent requests.
636 * @return Zend_Http_Client
638 public function resetParameters() {
639 // Reset parameter data
640 $this->paramsGet
= array();
641 $this->paramsPost
= array();
642 $this->files
= array();
643 $this->raw_post_data
= null;
645 // Clear outdated headers
646 if (isset($this->headers
['content-type'])) unset($this->headers
['content-type']);
647 if (isset($this->headers
['content-length'])) unset($this->headers
['content-length']);
653 * Get the last HTTP request as string
657 public function getLastRequest() {
658 return $this->last_request
;
662 * Get the last HTTP response received by this client
664 * If $config['storeresponse'] is set to false, or no response was
665 * stored yet, will return null
667 * @return Zend_Http_Response or null if none
669 public function getLastResponse() {
670 return $this->last_response
;
674 * Load the connection adapter
676 * While this method is not called more than one for a client, it is
677 * seperated from ->request() to preserve logic and readability
679 * @param Zend_Http_Client_Adapter_Interface|string $adapter
681 public function setAdapter($adapter) {
682 if (is_string($adapter)) {
684 Zend_Loader
::loadClass($adapter);
685 } catch (Zend_Exception
$e) {
686 require_once 'external/Zend/Http/Client/Exception.php';
687 throw new Zend_Http_Client_Exception("Unable to load adapter '$adapter': {$e->getMessage()}");
690 $adapter = new $adapter();
693 if (! $adapter instanceof Zend_Http_Client_Adapter_Interface
) {
694 require_once 'external/Zend/Http/Client/Exception.php';
695 throw new Zend_Http_Client_Exception('Passed adapter is not a HTTP connection adapter');
698 $this->adapter
= $adapter;
699 $config = $this->config
;
700 unset($config['adapter']);
701 $this->adapter
->setConfig($config);
705 * Send the HTTP request and return an HTTP response object
707 * @param string $method
708 * @return Zend_Http_Response
710 public function request($method = null) {
711 if (! $this->uri
instanceof Zend_Uri_Http
) {
712 require_once 'external/Zend/Http/Client/Exception.php';
713 throw new Zend_Http_Client_Exception('No valid URI has been passed to the client');
716 if ($method) $this->setMethod($method);
717 $this->redirectCounter
= 0;
720 // Make sure the adapter is loaded
721 if ($this->adapter
== null) $this->setAdapter($this->config
['adapter']);
723 // Send the first request. If redirected, continue.
725 // Clone the URI and add the additional GET parameters to it
726 $uri = clone $this->uri
;
727 if (! empty($this->paramsGet
)) {
728 $query = $uri->getQuery();
729 if (! empty($query)) $query .= '&';
730 $query .= http_build_query($this->paramsGet
, null, '&');
732 $uri->setQuery($query);
735 $body = $this->prepare_body();
736 $headers = $this->prepare_headers();
738 // Open the connection, send the request and read the response
739 $this->adapter
->connect($uri->getHost(), $uri->getPort(), ($uri->getScheme() == 'https' ?
true : false));
741 $this->last_request
= $this->adapter
->write($this->method
, $uri, $this->config
['httpversion'], $headers, $body);
743 $response = $this->adapter
->read();
745 require_once 'external/Zend/Http/Client/Exception.php';
746 throw new Zend_Http_Client_Exception('Unable to read response, or response is empty');
749 $response = Zend_Http_Response
::fromString($response);
750 if ($this->config
['storeresponse']) $this->last_response
= $response;
752 // Load cookies into cookie jar
753 if (isset($this->cookiejar
)) $this->cookiejar
->addCookiesFromResponse($response, $uri);
755 // If we got redirected, look for the Location header
756 if ($response->isRedirect() && ($location = $response->getHeader('location'))) {
758 // Check whether we send the exact same request again, or drop the parameters
759 // and send a GET request
760 if ($response->getStatus() == 303 ||
((! $this->config
['strictredirects']) && ($response->getStatus() == 302 ||
$response->getStatus() == 301))) {
762 $this->resetParameters();
763 $this->setMethod(self
::GET
);
766 // If we got a well formed absolute URI
767 if (Zend_Uri_Http
::check($location)) {
768 $this->setHeaders('host', null);
769 $this->setUri($location);
773 // Split into path and query and set the query
774 if (strpos($location, '?') !== false) {
775 list($location, $query) = explode('?', $location, 2);
779 $this->uri
->setQuery($query);
781 // Else, if we got just an absolute path, set it
782 if (strpos($location, '/') === 0) {
783 $this->uri
->setPath($location);
785 // Else, assume we have a relative path
787 // Get the current path directory, removing any trailing slashes
788 $path = $this->uri
->getPath();
789 $path = rtrim(substr($path, 0, strrpos($path, '/')), "/");
790 $this->uri
->setPath($path . '/' . $location);
793 ++
$this->redirectCounter
;
796 // If we didn't get any location, stop redirecting
800 } while ($this->redirectCounter
< $this->config
['maxredirects']);
806 * Prepare the request headers
810 protected function prepare_headers() {
813 // Set the host header
814 if (! isset($this->headers
['host'])) {
815 $host = $this->uri
->getHost();
817 // If the port is not default, add it
818 if (! (($this->uri
->getScheme() == 'http' && $this->uri
->getPort() == 80) ||
($this->uri
->getScheme() == 'https' && $this->uri
->getPort() == 443))) {
819 $host .= ':' . $this->uri
->getPort();
822 $headers[] = "Host: {$host}";
825 // Set the connection header
826 if (! isset($this->headers
['connection'])) {
827 if (! $this->config
['keepalive']) $headers[] = "Connection: close";
830 // Set the Accept-encoding header if not set - depending on whether
831 // zlib is available or not.
832 if (! isset($this->headers
['accept-encoding'])) {
833 if (function_exists('gzinflate')) {
834 $headers[] = 'Accept-encoding: gzip, deflate';
836 $headers[] = 'Accept-encoding: identity';
840 // Set the content-type header
841 if ($this->method
== self
::POST
&& (! isset($this->headers
['content-type']) && isset($this->enctype
))) {
843 $headers[] = "Content-type: {$this->enctype}";
846 // Set the user agent header
847 if (! isset($this->headers
['user-agent']) && isset($this->config
['useragent'])) {
848 $headers[] = "User-agent: {$this->config['useragent']}";
851 // Set HTTP authentication if needed
852 if (is_array($this->auth
)) {
853 $auth = self
::encodeAuthHeader($this->auth
['user'], $this->auth
['password'], $this->auth
['type']);
854 $headers[] = "Authorization: {$auth}";
857 // Load cookies from cookie jar
858 if (isset($this->cookiejar
)) {
859 $cookstr = $this->cookiejar
->getMatchingCookies($this->uri
, true, Zend_Http_CookieJar
::COOKIE_STRING_CONCAT
);
861 if ($cookstr) $headers[] = "Cookie: {$cookstr}";
864 // Add all other user defined headers
865 foreach ($this->headers
as $header) {
866 list($name, $value) = $header;
867 if (is_array($value)) $value = implode(', ', $value);
869 $headers[] = "$name: $value";
876 * Prepare the request body (for POST and PUT requests)
880 protected function prepare_body() {
881 // According to RFC2616, a TRACE request should not have a body.
882 if ($this->method
== self
::TRACE
) {
886 // If we have raw_post_data set, just use it as the body.
887 if (isset($this->raw_post_data
)) {
888 $this->setHeaders('Content-length', strlen($this->raw_post_data
));
889 return $this->raw_post_data
;
894 // If we have files to upload, force enctype to multipart/form-data
895 if (count($this->files
) > 0) $this->setEncType(self
::ENC_FORMDATA
);
897 // If we have POST parameters or files, encode and add them to the body
898 if (count($this->paramsPost
) > 0 ||
count($this->files
) > 0) {
899 switch ($this->enctype
) {
900 case self
::ENC_FORMDATA
:
901 // Encode body as multipart/form-data
902 $boundary = '---ZENDHTTPCLIENT-' . md5(microtime());
903 $this->setHeaders('Content-type', self
::ENC_FORMDATA
. "; boundary={$boundary}");
905 // Get POST parameters and encode them
906 $params = $this->_getParametersRecursive($this->paramsPost
);
907 foreach ($params as $pp) {
908 $body .= self
::encodeFormData($boundary, $pp[0], $pp[1]);
912 foreach ($this->files
as $name => $file) {
913 $fhead = array('Content-type' => $file[1]);
914 $body .= self
::encodeFormData($boundary, $name, $file[2], $file[0], $fhead);
917 $body .= "--{$boundary}--\r\n";
920 case self
::ENC_URLENCODED
:
921 // Encode body as application/x-www-form-urlencoded
922 $this->setHeaders('Content-type', self
::ENC_URLENCODED
);
923 $body = http_build_query($this->paramsPost
, '', '&');
927 require_once 'external/Zend/Http/Client/Exception.php';
928 throw new Zend_Http_Client_Exception("Cannot handle content type '{$this->enctype}' automatically." . " Please use Zend_Http_Client::setRawData to send this kind of content.");
933 if ($body) $this->setHeaders('Content-length', strlen($body));
938 * Helper method that gets a possibly multi-level parameters array (get or
939 * post) and flattens it.
941 * The method returns an array of (key, value) pairs (because keys are not
942 * necessarily unique. If one of the parameters in as array, it will also
943 * add a [] suffix to the key.
945 * @param array $parray The parameters array
946 * @param bool $urlencode Whether to urlencode the name and value
949 protected function _getParametersRecursive($parray, $urlencode = false) {
950 if (! is_array($parray)) return $parray;
951 $parameters = array();
953 foreach ($parray as $name => $value) {
954 if ($urlencode) $name = urlencode($name);
956 // If $value is an array, iterate over it
957 if (is_array($value)) {
958 $name .= ($urlencode ?
'%5B%5D' : '[]');
959 foreach ($value as $subval) {
960 if ($urlencode) $subval = urlencode($subval);
961 $parameters[] = array($name, $subval);
964 if ($urlencode) $value = urlencode($value);
965 $parameters[] = array($name, $value);
973 * Encode data to a multipart/form-data part suitable for a POST request.
975 * @param string $boundary
976 * @param string $name
977 * @param mixed $value
978 * @param string $filename
979 * @param array $headers Associative array of optional headers @example ("Content-transfer-encoding" => "binary")
982 public static function encodeFormData($boundary, $name, $value, $filename = null, $headers = array()) {
983 $ret = "--{$boundary}\r\n" . 'Content-disposition: form-data; name="' . $name . '"';
985 if ($filename) $ret .= '; filename="' . $filename . '"';
988 foreach ($headers as $hname => $hvalue) {
989 $ret .= "{$hname}: {$hvalue}\r\n";
993 $ret .= "{$value}\r\n";
999 * Create a HTTP authentication "Authorization:" header according to the
1000 * specified user, password and authentication method.
1002 * @see http://www.faqs.org/rfcs/rfc2617.html
1003 * @param string $user
1004 * @param string $password
1005 * @param string $type
1008 public static function encodeAuthHeader($user, $password, $type = self
::AUTH_BASIC
) {
1012 case self
::AUTH_BASIC
:
1013 // In basic authentication, the user name cannot contain ":"
1014 if (strpos($user, ':') !== false) {
1015 require_once 'external/Zend/Http/Client/Exception.php';
1016 throw new Zend_Http_Client_Exception("The user name cannot contain ':' in 'Basic' HTTP authentication");
1019 $authHeader = 'Basic ' . base64_encode($user . ':' . $password);
1022 //case self::AUTH_DIGEST:
1024 * @todo Implement digest authentication
1030 require_once 'external/Zend/Http/Client/Exception.php';
1031 throw new Zend_Http_Client_Exception("Not a supported HTTP authentication type: '$type'");