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 12504 2008-11-10 16:28:46Z matthew $
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
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
* Zend_Http_Client is an implemetation of an HTTP client in PHP. The client
49
* supports basic features like sending different HTTP requests and handling
50
* redirections, as well as more advanced features like proxy settings, HTTP
51
* authentication and cookie persistance (using a Zend_Http_CookieJar object)
53
* @todo Implement proxy settings
57
* @throws Zend_Http_Client_Exception
58
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
59
* @license http://framework.zend.com/license/new-bsd New BSD License
61
class Zend_Http_Client
64
* HTTP request methods
70
const DELETE = 'DELETE';
71
const TRACE = 'TRACE';
72
const OPTIONS = 'OPTIONS';
73
const CONNECT = 'CONNECT';
76
* Supported HTTP Authentication methods
78
const AUTH_BASIC = 'basic';
79
//const AUTH_DIGEST = 'digest'; <-- not implemented yet
82
* HTTP protocol versions
90
const CONTENT_TYPE = 'Content-Type';
91
const CONTENT_LENGTH = 'Content-Length';
94
* POST data encoding methods
96
const ENC_URLENCODED = 'application/x-www-form-urlencoded';
97
const ENC_FORMDATA = 'multipart/form-data';
100
* Configuration array, set using the constructor or using ::setConfig()
104
protected $config = array(
106
'strictredirects' => false,
107
'useragent' => 'Zend_Http_Client',
109
'adapter' => 'Zend_Http_Client_Adapter_Socket',
110
'httpversion' => self::HTTP_1,
111
'keepalive' => false,
112
'storeresponse' => true,
117
* The adapter used to preform the actual connection to the server
119
* @var Zend_Http_Client_Adapter_Interface
121
protected $adapter = null;
131
* Associative array of request headers
135
protected $headers = array();
138
* HTTP request method
142
protected $method = self::GET;
145
* Associative array of GET parameters
149
protected $paramsGet = array();
152
* Assiciative array of POST parameters
156
protected $paramsPost = array();
159
* Request body content type (for POST requests)
163
protected $enctype = null;
166
* The raw post data to send. Could be set by setRawData($data, $enctype).
170
protected $raw_post_data = null;
173
* HTTP Authentication settings
175
* Expected to be an associative array with this structure:
176
* $this->auth = array('user' => 'username', 'password' => 'password', 'type' => 'basic')
177
* Where 'type' should be one of the supported authentication types (see the AUTH_*
178
* constants), for example 'basic' or 'digest'.
180
* If null, no authentication will be used.
187
* File upload arrays (used in POST requests)
189
* An associative array, where each element is of the format:
190
* 'name' => array('filename.txt', 'text/plain', 'This is the actual file contents')
194
protected $files = array();
197
* The client's cookie jar
199
* @var Zend_Http_CookieJar
201
protected $cookiejar = null;
204
* The last HTTP request sent by the client, as string
208
protected $last_request = null;
211
* The last HTTP response received by the client
213
* @var Zend_Http_Response
215
protected $last_response = null;
218
* Redirection counter
222
protected $redirectCounter = 0;
225
* Fileinfo magic database resource
227
* This varaiable is populated the first time _detectFileMimeType is called
228
* and is then reused on every call to this method
232
static protected $_fileInfoDb = null;
235
* Contructor method. Will create a new HTTP client. Accepts the target
236
* URL and optionally configuration array.
238
* @param Zend_Uri_Http|string $uri
239
* @param array $config Configuration key-value pairs.
241
public function __construct($uri = null, $config = null)
243
if ($uri !== null) $this->setUri($uri);
244
if ($config !== null) $this->setConfig($config);
248
* Set the URI for the next request
250
* @param Zend_Uri_Http|string $uri
251
* @return Zend_Http_Client
252
* @throws Zend_Http_Client_Exception
254
public function setUri($uri)
256
if (is_string($uri)) {
257
$uri = Zend_Uri::factory($uri);
260
if (!$uri instanceof Zend_Uri_Http) {
261
/** @see Zend_Http_Client_Exception */
262
require_once 'Zend/Http/Client/Exception.php';
263
throw new Zend_Http_Client_Exception('Passed parameter is not a valid HTTP URI.');
266
// We have no ports, set the defaults
267
if (! $uri->getPort()) {
268
$uri->setPort(($uri->getScheme() == 'https' ? 443 : 80));
277
* Get the URI for the next request
279
* @param boolean $as_string If true, will return the URI as a string
280
* @return Zend_Uri_Http|string
282
public function getUri($as_string = false)
284
if ($as_string && $this->uri instanceof Zend_Uri_Http) {
285
return $this->uri->__toString();
292
* Set configuration parameters for this HTTP client
294
* @param array $config
295
* @return Zend_Http_Client
296
* @throws Zend_Http_Client_Exception
298
public function setConfig($config = array())
300
if (! is_array($config)) {
301
/** @see Zend_Http_Client_Exception */
302
require_once 'Zend/Http/Client/Exception.php';
303
throw new Zend_Http_Client_Exception('Expected array parameter, given ' . gettype($config));
306
foreach ($config as $k => $v)
307
$this->config[strtolower($k)] = $v;
309
// Pass configuration options to the adapter if it exists
310
if ($this->adapter instanceof Zend_Http_Client_Adapter_Interface) {
311
$this->adapter->setConfig($config);
318
* Set the next request's method
320
* Validated the passed method and sets it. If we have files set for
321
* POST requests, and the new method is not POST, the files are silently
324
* @param string $method
325
* @return Zend_Http_Client
326
* @throws Zend_Http_Client_Exception
328
public function setMethod($method = self::GET)
330
$regex = '/^[^\x00-\x1f\x7f-\xff\(\)<>@,;:\\\\"\/\[\]\?={}\s]+$/';
331
if (! preg_match($regex, $method)) {
332
/** @see Zend_Http_Client_Exception */
333
require_once 'Zend/Http/Client/Exception.php';
334
throw new Zend_Http_Client_Exception("'{$method}' is not a valid HTTP request method.");
337
if ($method == self::POST && $this->enctype === null)
338
$this->setEncType(self::ENC_URLENCODED);
340
$this->method = $method;
346
* Set one or more request headers
348
* This function can be used in several ways to set the client's request
350
* 1. By providing two parameters: $name as the header to set (eg. 'Host')
351
* and $value as it's value (eg. 'www.example.com').
352
* 2. By providing a single header string as the only parameter
353
* eg. 'Host: www.example.com'
354
* 3. By providing an array of headers as the first parameter
355
* eg. array('host' => 'www.example.com', 'x-foo: bar'). In This case
356
* the function will call itself recursively for each array item.
358
* @param string|array $name Header name, full header string ('Header: value')
359
* or an array of headers
360
* @param mixed $value Header value or null
361
* @return Zend_Http_Client
362
* @throws Zend_Http_Client_Exception
364
public function setHeaders($name, $value = null)
366
// If we got an array, go recusive!
367
if (is_array($name)) {
368
foreach ($name as $k => $v) {
370
$this->setHeaders($k, $v);
372
$this->setHeaders($v, null);
376
// Check if $name needs to be split
377
if ($value === null && (strpos($name, ':') > 0))
378
list($name, $value) = explode(':', $name, 2);
380
// Make sure the name is valid if we are in strict mode
381
if ($this->config['strict'] && (! preg_match('/^[a-zA-Z0-9-]+$/', $name))) {
382
/** @see Zend_Http_Client_Exception */
383
require_once 'Zend/Http/Client/Exception.php';
384
throw new Zend_Http_Client_Exception("{$name} is not a valid HTTP header name");
387
$normalized_name = strtolower($name);
389
// If $value is null or false, unset the header
390
if ($value === null || $value === false) {
391
unset($this->headers[$normalized_name]);
393
// Else, set the header
395
// Header names are storred lowercase internally.
396
if (is_string($value)) $value = trim($value);
397
$this->headers[$normalized_name] = array($name, $value);
405
* Get the value of a specific header
407
* Note that if the header has more than one value, an array
411
* @return string|array|null The header value or null if it is not set
413
public function getHeader($key)
415
$key = strtolower($key);
416
if (isset($this->headers[$key])) {
417
return $this->headers[$key][1];
424
* Set a GET parameter for the request. Wrapper around _setParameter
426
* @param string|array $name
427
* @param string $value
428
* @return Zend_Http_Client
430
public function setParameterGet($name, $value = null)
432
if (is_array($name)) {
433
foreach ($name as $k => $v)
434
$this->_setParameter('GET', $k, $v);
436
$this->_setParameter('GET', $name, $value);
443
* Set a POST parameter for the request. Wrapper around _setParameter
445
* @param string|array $name
446
* @param string $value
447
* @return Zend_Http_Client
449
public function setParameterPost($name, $value = null)
451
if (is_array($name)) {
452
foreach ($name as $k => $v)
453
$this->_setParameter('POST', $k, $v);
455
$this->_setParameter('POST', $name, $value);
462
* Set a GET or POST parameter - used by SetParameterGet and SetParameterPost
464
* @param string $type GET or POST
465
* @param string $name
466
* @param string $value
469
protected function _setParameter($type, $name, $value)
472
$type = strtolower($type);
475
$parray = &$this->paramsGet;
478
$parray = &$this->paramsPost;
482
if ($value === null) {
483
if (isset($parray[$name])) unset($parray[$name]);
485
$parray[$name] = $value;
490
* Get the number of redirections done on the last request
494
public function getRedirectionsCount()
496
return $this->redirectCounter;
500
* Set HTTP authentication parameters
502
* $type should be one of the supported types - see the self::AUTH_*
505
* To enable authentication:
507
* $this->setAuth('shahar', 'secret', Zend_Http_Client::AUTH_BASIC);
510
* To disable authentication:
512
* $this->setAuth(false);
515
* @see http://www.faqs.org/rfcs/rfc2617.html
516
* @param string|false $user User name or false disable authentication
517
* @param string $password Password
518
* @param string $type Authentication type
519
* @return Zend_Http_Client
520
* @throws Zend_Http_Client_Exception
522
public function setAuth($user, $password = '', $type = self::AUTH_BASIC)
524
// If we got false or null, disable authentication
525
if ($user === false || $user === null) {
528
// Else, set up authentication
530
// Check we got a proper authentication type
531
if (! defined('self::AUTH_' . strtoupper($type))) {
532
/** @see Zend_Http_Client_Exception */
533
require_once 'Zend/Http/Client/Exception.php';
534
throw new Zend_Http_Client_Exception("Invalid or not supported authentication type: '$type'");
538
'user' => (string) $user,
539
'password' => (string) $password,
548
* Set the HTTP client's cookie jar.
550
* A cookie jar is an object that holds and maintains cookies across HTTP requests
553
* @param Zend_Http_CookieJar|boolean $cookiejar Existing cookiejar object, true to create a new one, false to disable
554
* @return Zend_Http_Client
555
* @throws Zend_Http_Client_Exception
557
public function setCookieJar($cookiejar = true)
559
if (! class_exists('Zend_Http_CookieJar'))
560
require_once 'Zend/Http/CookieJar.php';
562
if ($cookiejar instanceof Zend_Http_CookieJar) {
563
$this->cookiejar = $cookiejar;
564
} elseif ($cookiejar === true) {
565
$this->cookiejar = new Zend_Http_CookieJar();
566
} elseif (! $cookiejar) {
567
$this->cookiejar = null;
569
/** @see Zend_Http_Client_Exception */
570
require_once 'Zend/Http/Client/Exception.php';
571
throw new Zend_Http_Client_Exception('Invalid parameter type passed as CookieJar');
578
* Return the current cookie jar or null if none.
580
* @return Zend_Http_CookieJar|null
582
public function getCookieJar()
584
return $this->cookiejar;
588
* Add a cookie to the request. If the client has no Cookie Jar, the cookies
589
* will be added directly to the headers array as "Cookie" headers.
591
* @param Zend_Http_Cookie|string $cookie
592
* @param string|null $value If "cookie" is a string, this is the cookie value.
593
* @return Zend_Http_Client
594
* @throws Zend_Http_Client_Exception
596
public function setCookie($cookie, $value = null)
598
if (! class_exists('Zend_Http_Cookie'))
599
require_once 'Zend/Http/Cookie.php';
601
if (is_array($cookie)) {
602
foreach ($cookie as $c => $v) {
604
$this->setCookie($c, $v);
606
$this->setCookie($v);
613
if ($value !== null) $value = urlencode($value);
615
if (isset($this->cookiejar)) {
616
if ($cookie instanceof Zend_Http_Cookie) {
617
$this->cookiejar->addCookie($cookie);
618
} elseif (is_string($cookie) && $value !== null) {
619
$cookie = Zend_Http_Cookie::fromString("{$cookie}={$value}", $this->uri);
620
$this->cookiejar->addCookie($cookie);
623
if ($cookie instanceof Zend_Http_Cookie) {
624
$name = $cookie->getName();
625
$value = $cookie->getValue();
629
if (preg_match("/[=,; \t\r\n\013\014]/", $cookie)) {
630
/** @see Zend_Http_Client_Exception */
631
require_once 'Zend/Http/Client/Exception.php';
632
throw new Zend_Http_Client_Exception("Cookie name cannot contain these characters: =,; \t\r\n\013\014 ({$cookie})");
635
$value = addslashes($value);
637
if (! isset($this->headers['cookie'])) $this->headers['cookie'] = array('Cookie', '');
638
$this->headers['cookie'][1] .= $cookie . '=' . $value . '; ';
645
* Set a file to upload (using a POST request)
647
* Can be used in two ways:
649
* 1. $data is null (default): $filename is treated as the name if a local file which
650
* will be read and sent. Will try to guess the content type using mime_content_type().
651
* 2. $data is set - $filename is sent as the file name, but $data is sent as the file
652
* contents and no file is read from the file system. In this case, you need to
653
* manually set the Content-Type ($ctype) or it will default to
654
* application/octet-stream.
656
* @param string $filename Name of file to upload, or name to save as
657
* @param string $formname Name of form element to send as
658
* @param string $data Data to send (if null, $filename is read and sent)
659
* @param string $ctype Content type to use (if $data is set and $ctype is
660
* null, will be application/octet-stream)
661
* @return Zend_Http_Client
662
* @throws Zend_Http_Client_Exception
664
public function setFileUpload($filename, $formname, $data = null, $ctype = null)
666
if ($data === null) {
667
if (($data = @file_get_contents($filename)) === false) {
668
/** @see Zend_Http_Client_Exception */
669
require_once 'Zend/Http/Client/Exception.php';
670
throw new Zend_Http_Client_Exception("Unable to read file '{$filename}' for upload");
673
if (! $ctype) $ctype = $this->_detectFileMimeType($filename);
676
// Force enctype to multipart/form-data
677
$this->setEncType(self::ENC_FORMDATA);
679
$this->files[$formname] = array(basename($filename), $ctype, $data);
685
* Set the encoding type for POST data
687
* @param string $enctype
688
* @return Zend_Http_Client
690
public function setEncType($enctype = self::ENC_URLENCODED)
692
$this->enctype = $enctype;
698
* Set the raw (already encoded) POST data.
700
* This function is here for two reasons:
701
* 1. For advanced user who would like to set their own data, already encoded
702
* 2. For backwards compatibilty: If someone uses the old post($data) method.
703
* this method will be used to set the encoded data.
705
* @param string $data
706
* @param string $enctype
707
* @return Zend_Http_Client
709
public function setRawData($data, $enctype = null)
711
$this->raw_post_data = $data;
712
$this->setEncType($enctype);
718
* Clear all GET and POST parameters
720
* Should be used to reset the request parameters if the client is
721
* used for several concurrent requests.
723
* @return Zend_Http_Client
725
public function resetParameters()
727
// Reset parameter data
728
$this->paramsGet = array();
729
$this->paramsPost = array();
730
$this->files = array();
731
$this->raw_post_data = null;
733
// Clear outdated headers
734
if (isset($this->headers[strtolower(self::CONTENT_TYPE)]))
735
unset($this->headers[strtolower(self::CONTENT_TYPE)]);
736
if (isset($this->headers[strtolower(self::CONTENT_LENGTH)]))
737
unset($this->headers[strtolower(self::CONTENT_LENGTH)]);
743
* Get the last HTTP request as string
747
public function getLastRequest()
749
return $this->last_request;
753
* Get the last HTTP response received by this client
755
* If $config['storeresponse'] is set to false, or no response was
756
* stored yet, will return null
758
* @return Zend_Http_Response or null if none
760
public function getLastResponse()
762
return $this->last_response;
766
* Load the connection adapter
768
* While this method is not called more than one for a client, it is
769
* seperated from ->request() to preserve logic and readability
771
* @param Zend_Http_Client_Adapter_Interface|string $adapter
773
* @throws Zend_Http_Client_Exception
775
public function setAdapter($adapter)
777
if (is_string($adapter)) {
779
Zend_Loader::loadClass($adapter);
780
} catch (Zend_Exception $e) {
781
/** @see Zend_Http_Client_Exception */
782
require_once 'Zend/Http/Client/Exception.php';
783
throw new Zend_Http_Client_Exception("Unable to load adapter '$adapter': {$e->getMessage()}");
786
$adapter = new $adapter;
789
if (! $adapter instanceof Zend_Http_Client_Adapter_Interface) {
790
/** @see Zend_Http_Client_Exception */
791
require_once 'Zend/Http/Client/Exception.php';
792
throw new Zend_Http_Client_Exception('Passed adapter is not a HTTP connection adapter');
795
$this->adapter = $adapter;
796
$config = $this->config;
797
unset($config['adapter']);
798
$this->adapter->setConfig($config);
802
* Send the HTTP request and return an HTTP response object
804
* @param string $method
805
* @return Zend_Http_Response
806
* @throws Zend_Http_Client_Exception
808
public function request($method = null)
810
if (! $this->uri instanceof Zend_Uri_Http) {
811
/** @see Zend_Http_Client_Exception */
812
require_once 'Zend/Http/Client/Exception.php';
813
throw new Zend_Http_Client_Exception('No valid URI has been passed to the client');
816
if ($method) $this->setMethod($method);
817
$this->redirectCounter = 0;
820
// Make sure the adapter is loaded
821
if ($this->adapter == null) $this->setAdapter($this->config['adapter']);
823
// Send the first request. If redirected, continue.
825
// Clone the URI and add the additional GET parameters to it
826
$uri = clone $this->uri;
827
if (! empty($this->paramsGet)) {
828
$query = $uri->getQuery();
829
if (! empty($query)) $query .= '&';
830
$query .= http_build_query($this->paramsGet, null, '&');
832
$uri->setQuery($query);
835
$body = $this->_prepareBody();
836
$headers = $this->_prepareHeaders();
838
// Open the connection, send the request and read the response
839
$this->adapter->connect($uri->getHost(), $uri->getPort(),
840
($uri->getScheme() == 'https' ? true : false));
842
$this->last_request = $this->adapter->write($this->method,
843
$uri, $this->config['httpversion'], $headers, $body);
845
$response = $this->adapter->read();
847
/** @see Zend_Http_Client_Exception */
848
require_once 'Zend/Http/Client/Exception.php';
849
throw new Zend_Http_Client_Exception('Unable to read response, or response is empty');
852
$response = Zend_Http_Response::fromString($response);
853
if ($this->config['storeresponse']) $this->last_response = $response;
855
// Load cookies into cookie jar
856
if (isset($this->cookiejar)) $this->cookiejar->addCookiesFromResponse($response, $uri);
858
// If we got redirected, look for the Location header
859
if ($response->isRedirect() && ($location = $response->getHeader('location'))) {
861
// Check whether we send the exact same request again, or drop the parameters
862
// and send a GET request
863
if ($response->getStatus() == 303 ||
864
((! $this->config['strictredirects']) && ($response->getStatus() == 302 ||
865
$response->getStatus() == 301))) {
867
$this->resetParameters();
868
$this->setMethod(self::GET);
871
// If we got a well formed absolute URI
872
if (Zend_Uri_Http::check($location)) {
873
$this->setHeaders('host', null);
874
$this->setUri($location);
878
// Split into path and query and set the query
879
if (strpos($location, '?') !== false) {
880
list($location, $query) = explode('?', $location, 2);
884
$this->uri->setQuery($query);
886
// Else, if we got just an absolute path, set it
887
if(strpos($location, '/') === 0) {
888
$this->uri->setPath($location);
890
// Else, assume we have a relative path
892
// Get the current path directory, removing any trailing slashes
893
$path = $this->uri->getPath();
894
$path = rtrim(substr($path, 0, strrpos($path, '/')), "/");
895
$this->uri->setPath($path . '/' . $location);
898
++$this->redirectCounter;
901
// If we didn't get any location, stop redirecting
905
} while ($this->redirectCounter < $this->config['maxredirects']);
911
* Prepare the request headers
915
protected function _prepareHeaders()
919
// Set the host header
920
if (! isset($this->headers['host'])) {
921
$host = $this->uri->getHost();
923
// If the port is not default, add it
924
if (! (($this->uri->getScheme() == 'http' && $this->uri->getPort() == 80) ||
925
($this->uri->getScheme() == 'https' && $this->uri->getPort() == 443))) {
926
$host .= ':' . $this->uri->getPort();
929
$headers[] = "Host: {$host}";
932
// Set the connection header
933
if (! isset($this->headers['connection'])) {
934
if (! $this->config['keepalive']) $headers[] = "Connection: close";
937
// Set the Accept-encoding header if not set - depending on whether
938
// zlib is available or not.
939
if (! isset($this->headers['accept-encoding'])) {
940
if (function_exists('gzinflate')) {
941
$headers[] = 'Accept-encoding: gzip, deflate';
943
$headers[] = 'Accept-encoding: identity';
947
// Set the Content-Type header
948
if ($this->method == self::POST &&
949
(! isset($this->headers[strtolower(self::CONTENT_TYPE)]) && isset($this->enctype))) {
951
$headers[] = self::CONTENT_TYPE . ': ' . $this->enctype;
954
// Set the user agent header
955
if (! isset($this->headers['user-agent']) && isset($this->config['useragent'])) {
956
$headers[] = "User-Agent: {$this->config['useragent']}";
959
// Set HTTP authentication if needed
960
if (is_array($this->auth)) {
961
$auth = self::encodeAuthHeader($this->auth['user'], $this->auth['password'], $this->auth['type']);
962
$headers[] = "Authorization: {$auth}";
965
// Load cookies from cookie jar
966
if (isset($this->cookiejar)) {
967
$cookstr = $this->cookiejar->getMatchingCookies($this->uri,
968
true, Zend_Http_CookieJar::COOKIE_STRING_CONCAT);
970
if ($cookstr) $headers[] = "Cookie: {$cookstr}";
973
// Add all other user defined headers
974
foreach ($this->headers as $header) {
975
list($name, $value) = $header;
976
if (is_array($value))
977
$value = implode(', ', $value);
979
$headers[] = "$name: $value";
986
* Prepare the request body (for POST and PUT requests)
989
* @throws Zend_Http_Client_Exception
991
protected function _prepareBody()
993
// According to RFC2616, a TRACE request should not have a body.
994
if ($this->method == self::TRACE) {
998
// If we have raw_post_data set, just use it as the body.
999
if (isset($this->raw_post_data)) {
1000
$this->setHeaders(self::CONTENT_LENGTH, strlen($this->raw_post_data));
1001
return $this->raw_post_data;
1006
// If we have files to upload, force enctype to multipart/form-data
1007
if (count ($this->files) > 0) $this->setEncType(self::ENC_FORMDATA);
1009
// If we have POST parameters or files, encode and add them to the body
1010
if (count($this->paramsPost) > 0 || count($this->files) > 0) {
1011
switch($this->enctype) {
1012
case self::ENC_FORMDATA:
1013
// Encode body as multipart/form-data
1014
$boundary = '---ZENDHTTPCLIENT-' . md5(microtime());
1015
$this->setHeaders(self::CONTENT_TYPE, self::ENC_FORMDATA . "; boundary={$boundary}");
1017
// Get POST parameters and encode them
1018
$params = $this->_getParametersRecursive($this->paramsPost);
1019
foreach ($params as $pp) {
1020
$body .= self::encodeFormData($boundary, $pp[0], $pp[1]);
1024
foreach ($this->files as $name => $file) {
1025
$fhead = array(self::CONTENT_TYPE => $file[1]);
1026
$body .= self::encodeFormData($boundary, $name, $file[2], $file[0], $fhead);
1029
$body .= "--{$boundary}--\r\n";
1032
case self::ENC_URLENCODED:
1033
// Encode body as application/x-www-form-urlencoded
1034
$this->setHeaders(self::CONTENT_TYPE, self::ENC_URLENCODED);
1035
$body = http_build_query($this->paramsPost, '', '&');
1039
/** @see Zend_Http_Client_Exception */
1040
require_once 'Zend/Http/Client/Exception.php';
1041
throw new Zend_Http_Client_Exception("Cannot handle content type '{$this->enctype}' automatically." .
1042
" Please use Zend_Http_Client::setRawData to send this kind of content.");
1047
// Set the Content-Length if we have a body or if request is POST/PUT
1048
if ($body || $this->method == self::POST || $this->method == self::PUT) {
1049
$this->setHeaders(self::CONTENT_LENGTH, strlen($body));
1056
* Helper method that gets a possibly multi-level parameters array (get or
1057
* post) and flattens it.
1059
* The method returns an array of (key, value) pairs (because keys are not
1060
* necessarily unique. If one of the parameters in as array, it will also
1061
* add a [] suffix to the key.
1063
* @param array $parray The parameters array
1064
* @param bool $urlencode Whether to urlencode the name and value
1067
protected function _getParametersRecursive($parray, $urlencode = false)
1069
if (! is_array($parray)) return $parray;
1070
$parameters = array();
1072
foreach ($parray as $name => $value) {
1073
if ($urlencode) $name = urlencode($name);
1075
// If $value is an array, iterate over it
1076
if (is_array($value)) {
1077
$name .= ($urlencode ? '%5B%5D' : '[]');
1078
foreach ($value as $subval) {
1079
if ($urlencode) $subval = urlencode($subval);
1080
$parameters[] = array($name, $subval);
1083
if ($urlencode) $value = urlencode($value);
1084
$parameters[] = array($name, $value);
1092
* Attempt to detect the MIME type of a file using available extensions
1094
* This method will try to detect the MIME type of a file. If the fileinfo
1095
* extension is available, it will be used. If not, the mime_magic
1096
* extension which is deprected but is still available in many PHP setups
1099
* If neither extension is available, the default application/octet-stream
1100
* MIME type will be returned
1102
* @param string $file File path
1103
* @return string MIME type
1105
protected function _detectFileMimeType($file)
1109
// First try with fileinfo functions
1110
if (function_exists('finfo_open')) {
1111
if (self::$_fileInfoDb === null) {
1112
self::$_fileInfoDb = @finfo_open(FILEINFO_MIME);
1115
if (self::$_fileInfoDb) {
1116
$type = finfo_file(self::$_fileInfoDb, $file);
1119
} elseif (function_exists('mime_content_type')) {
1120
$type = mime_content_type($file);
1123
// Fallback to the default application/octet-stream
1125
$type = 'application/octet-stream';
1132
* Encode data to a multipart/form-data part suitable for a POST request.
1134
* @param string $boundary
1135
* @param string $name
1136
* @param mixed $value
1137
* @param string $filename
1138
* @param array $headers Associative array of optional headers @example ("Content-Transfer-Encoding" => "binary")
1141
public static function encodeFormData($boundary, $name, $value, $filename = null, $headers = array()) {
1142
$ret = "--{$boundary}\r\n" .
1143
'Content-Disposition: form-data; name="' . $name .'"';
1145
if ($filename) $ret .= '; filename="' . $filename . '"';
1148
foreach ($headers as $hname => $hvalue) {
1149
$ret .= "{$hname}: {$hvalue}\r\n";
1153
$ret .= "{$value}\r\n";
1159
* Create a HTTP authentication "Authorization:" header according to the
1160
* specified user, password and authentication method.
1162
* @see http://www.faqs.org/rfcs/rfc2617.html
1163
* @param string $user
1164
* @param string $password
1165
* @param string $type
1167
* @throws Zend_Http_Client_Exception
1169
public static function encodeAuthHeader($user, $password, $type = self::AUTH_BASIC)
1174
case self::AUTH_BASIC:
1175
// In basic authentication, the user name cannot contain ":"
1176
if (strpos($user, ':') !== false) {
1177
/** @see Zend_Http_Client_Exception */
1178
require_once 'Zend/Http/Client/Exception.php';
1179
throw new Zend_Http_Client_Exception("The user name cannot contain ':' in 'Basic' HTTP authentication");
1182
$authHeader = 'Basic ' . base64_encode($user . ':' . $password);
1185
//case self::AUTH_DIGEST:
1187
* @todo Implement digest authentication
1192
/** @see Zend_Http_Client_Exception */
1193
require_once 'Zend/Http/Client/Exception.php';
1194
throw new Zend_Http_Client_Exception("Not a supported HTTP authentication type: '$type'");