Curl.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Http
  17. * @subpackage Client_Adapter
  18. * @version $Id$
  19. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  20. * @license http://framework.zend.com/license/new-bsd New BSD License
  21. */
  22. /**
  23. * @see Zend_Uri_Http
  24. */
  25. require_once 'Zend/Uri/Http.php';
  26. /**
  27. * @see Zend_Http_Client_Adapter_Interface
  28. */
  29. require_once 'Zend/Http/Client/Adapter/Interface.php';
  30. /**
  31. * An adapter class for Zend_Http_Client based on the curl extension.
  32. * Curl requires libcurl. See for full requirements the PHP manual: http://php.net/curl
  33. *
  34. * @category Zend
  35. * @package Zend_Http
  36. * @subpackage Client_Adapter
  37. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  38. * @license http://framework.zend.com/license/new-bsd New BSD License
  39. */
  40. class Zend_Http_Client_Adapter_Curl implements Zend_Http_Client_Adapter_Interface
  41. {
  42. /**
  43. * Parameters array
  44. *
  45. * @var array
  46. */
  47. protected $_config = array();
  48. /**
  49. * What host/port are we connected to?
  50. *
  51. * @var array
  52. */
  53. protected $_connected_to = array(null, null);
  54. /**
  55. * The curl session handle
  56. *
  57. * @var resource|null
  58. */
  59. protected $_curl = null;
  60. /**
  61. * List of cURL options that should never be overwritten
  62. *
  63. * @var array
  64. */
  65. protected $_invalidOverwritableCurlOptions = array(
  66. CURLOPT_HTTPGET,
  67. CURLOPT_POST,
  68. CURLOPT_PUT,
  69. CURLOPT_CUSTOMREQUEST,
  70. CURLOPT_HEADER,
  71. CURLOPT_RETURNTRANSFER,
  72. CURLOPT_HTTPHEADER,
  73. CURLOPT_POSTFIELDS,
  74. CURLOPT_INFILE,
  75. CURLOPT_INFILESIZE,
  76. CURLOPT_PORT,
  77. CURLOPT_MAXREDIRS,
  78. CURLOPT_CONNECTTIMEOUT,
  79. CURL_HTTP_VERSION_1_1,
  80. CURL_HTTP_VERSION_1_0,
  81. );
  82. /**
  83. * Response gotten from server
  84. *
  85. * @var string
  86. */
  87. protected $_response = null;
  88. /**
  89. * Adapter constructor
  90. *
  91. * Config is set using setConfig()
  92. *
  93. * @return void
  94. * @throws Zend_Http_Client_Adapter_Exception
  95. */
  96. public function __construct()
  97. {
  98. if (!extension_loaded('curl')) {
  99. require_once 'Zend/Http/Client/Adapter/Exception.php';
  100. throw new Zend_Http_Client_Adapter_Exception('cURL extension has to be loaded to use this Zend_Http_Client adapter.');
  101. }
  102. }
  103. /**
  104. * Set the configuration array for the adapter
  105. *
  106. * @throws Zend_Http_Client_Adapter_Exception
  107. * @param Zend_Config | array $config
  108. * @return Zend_Http_Client_Adapter_Curl
  109. */
  110. public function setConfig($config = array())
  111. {
  112. if ($config instanceof Zend_Config) {
  113. $config = $config->toArray();
  114. } elseif (! is_array($config)) {
  115. require_once 'Zend/Http/Client/Adapter/Exception.php';
  116. throw new Zend_Http_Client_Adapter_Exception(
  117. 'Array or Zend_Config object expected, got ' . gettype($config)
  118. );
  119. }
  120. if(isset($config['proxy_user']) && isset($config['proxy_pass'])) {
  121. $this->setCurlOption(CURLOPT_PROXYUSERPWD, $config['proxy_user'].":".$config['proxy_pass']);
  122. unset($config['proxy_user'], $config['proxy_pass']);
  123. }
  124. foreach ($config as $k => $v) {
  125. $option = strtolower($k);
  126. switch($option) {
  127. case 'proxy_host':
  128. $this->setCurlOption(CURLOPT_PROXY, $v);
  129. break;
  130. case 'proxy_port':
  131. $this->setCurlOption(CURLOPT_PROXYPORT, $v);
  132. break;
  133. default:
  134. $this->_config[$option] = $v;
  135. break;
  136. }
  137. }
  138. return $this;
  139. }
  140. /**
  141. * Direct setter for cURL adapter related options.
  142. *
  143. * @param string|int $option
  144. * @param mixed $value
  145. * @return Zend_Http_Adapter_Curl
  146. */
  147. public function setCurlOption($option, $value)
  148. {
  149. if (!isset($this->_config['curloptions'])) {
  150. $this->_config['curloptions'] = array();
  151. }
  152. $this->_config['curloptions'][$option] = $value;
  153. return $this;
  154. }
  155. /**
  156. * Initialize curl
  157. *
  158. * @param string $host
  159. * @param int $port
  160. * @param boolean $secure
  161. * @return void
  162. * @throws Zend_Http_Client_Adapter_Exception if unable to connect
  163. */
  164. public function connect($host, $port = 80, $secure = false)
  165. {
  166. // If we're already connected, disconnect first
  167. if ($this->_curl) {
  168. $this->close();
  169. }
  170. // If we are connected to a different server or port, disconnect first
  171. if ($this->_curl
  172. && is_array($this->_connected_to)
  173. && ($this->_connected_to[0] != $host
  174. || $this->_connected_to[1] != $port)
  175. ) {
  176. $this->close();
  177. }
  178. // Do the actual connection
  179. $this->_curl = curl_init();
  180. if ($port != 80) {
  181. curl_setopt($this->_curl, CURLOPT_PORT, intval($port));
  182. }
  183. // Set timeout
  184. curl_setopt($this->_curl, CURLOPT_CONNECTTIMEOUT, $this->_config['timeout']);
  185. // Set Max redirects
  186. curl_setopt($this->_curl, CURLOPT_MAXREDIRS, $this->_config['maxredirects']);
  187. if (!$this->_curl) {
  188. $this->close();
  189. require_once 'Zend/Http/Client/Adapter/Exception.php';
  190. throw new Zend_Http_Client_Adapter_Exception('Unable to Connect to ' . $host . ':' . $port);
  191. }
  192. if ($secure !== false) {
  193. // Behave the same like Zend_Http_Adapter_Socket on SSL options.
  194. if (isset($this->_config['sslcert'])) {
  195. curl_setopt($this->_curl, CURLOPT_SSLCERT, $this->_config['sslcert']);
  196. }
  197. if (isset($this->_config['sslpassphrase'])) {
  198. curl_setopt($this->_curl, CURLOPT_SSLCERTPASSWD, $this->_config['sslpassphrase']);
  199. }
  200. }
  201. // Update connected_to
  202. $this->_connected_to = array($host, $port);
  203. }
  204. /**
  205. * Send request to the remote server
  206. *
  207. * @param string $method
  208. * @param Zend_Uri_Http $uri
  209. * @param float $http_ver
  210. * @param array $headers
  211. * @param string $body
  212. * @return string $request
  213. * @throws Zend_Http_Client_Adapter_Exception If connection fails, connected to wrong host, no PUT file defined, unsupported method, or unsupported cURL option
  214. */
  215. public function write($method, $uri, $http_ver = '1.1', $headers = array(), $body = '')
  216. {
  217. // Make sure we're properly connected
  218. if (!$this->_curl) {
  219. require_once 'Zend/Http/Client/Adapter/Exception.php';
  220. throw new Zend_Http_Client_Adapter_Exception("Trying to write but we are not connected");
  221. }
  222. if ($this->_connected_to[0] != $uri->getHost() || $this->_connected_to[1] != $uri->getPort()) {
  223. require_once 'Zend/Http/Client/Adapter/Exception.php';
  224. throw new Zend_Http_Client_Adapter_Exception("Trying to write but we are connected to the wrong host");
  225. }
  226. // set URL
  227. curl_setopt($this->_curl, CURLOPT_URL, $uri->__toString());
  228. // ensure correct curl call
  229. $curlValue = true;
  230. switch ($method) {
  231. case Zend_Http_Client::GET:
  232. $curlMethod = CURLOPT_HTTPGET;
  233. break;
  234. case Zend_Http_Client::POST:
  235. $curlMethod = CURLOPT_POST;
  236. break;
  237. case Zend_Http_Client::PUT:
  238. // There are two different types of PUT request, either a Raw Data string has been set
  239. // or CURLOPT_INFILE and CURLOPT_INFILESIZE are used.
  240. if (isset($this->_config['curloptions'][CURLOPT_INFILE])) {
  241. if (!isset($this->_config['curloptions'][CURLOPT_INFILESIZE])) {
  242. require_once 'Zend/Http/Client/Adapter/Exception.php';
  243. throw new Zend_Http_Client_Adapter_Exception("Cannot set a file-handle for cURL option CURLOPT_INFILE without also setting its size in CURLOPT_INFILESIZE.");
  244. }
  245. // Now we will probably already have Content-Length set, so that we have to delete it
  246. // from $headers at this point:
  247. foreach ($headers AS $k => $header) {
  248. if (stristr($header, "Content-Length:") !== false) {
  249. unset($headers[$k]);
  250. }
  251. }
  252. $curlMethod = CURLOPT_PUT;
  253. } else {
  254. $curlMethod = CURLOPT_CUSTOMREQUEST;
  255. $curlValue = "PUT";
  256. }
  257. break;
  258. case Zend_Http_Client::DELETE:
  259. $curlMethod = CURLOPT_CUSTOMREQUEST;
  260. $curlValue = "DELETE";
  261. break;
  262. case Zend_Http_Client::OPTIONS:
  263. $curlMethod = CURLOPT_CUSTOMREQUEST;
  264. $curlValue = "OPTIONS";
  265. break;
  266. case Zend_Http_Client::TRACE:
  267. $curlMethod = CURLOPT_CUSTOMREQUEST;
  268. $curlValue = "TRACE";
  269. break;
  270. default:
  271. // For now, through an exception for unsupported request methods
  272. require_once 'Zend/Http/Client/Adapter/Exception.php';
  273. throw new Zend_Http_Client_Adapter_Exception("Method currently not supported");
  274. }
  275. // get http version to use
  276. $curlHttp = ($http_ver = 1.1) ? CURL_HTTP_VERSION_1_1 : CURL_HTTP_VERSION_1_0;
  277. // mark as HTTP request and set HTTP method
  278. curl_setopt($this->_curl, $curlHttp, true);
  279. curl_setopt($this->_curl, $curlMethod, $curlValue);
  280. // ensure headers are also returned
  281. curl_setopt($this->_curl, CURLOPT_HEADER, true);
  282. // ensure actual response is returned
  283. curl_setopt($this->_curl, CURLOPT_RETURNTRANSFER, true);
  284. // set additional headers
  285. $headers['Accept'] = '';
  286. curl_setopt($this->_curl, CURLOPT_HTTPHEADER, $headers);
  287. /**
  288. * Make sure POSTFIELDS is set after $curlMethod is set:
  289. * @link http://de2.php.net/manual/en/function.curl-setopt.php#81161
  290. */
  291. if ($method == Zend_Http_Client::POST) {
  292. curl_setopt($this->_curl, CURLOPT_POSTFIELDS, $body);
  293. } elseif ($curlMethod == CURLOPT_PUT) {
  294. // this covers a PUT by file-handle:
  295. // Make the setting of this options explicit (rather than setting it through the loop following a bit lower)
  296. // to group common functionality together.
  297. curl_setopt($this->_curl, CURLOPT_INFILE, $this->_config['curloptions'][CURLOPT_INFILE]);
  298. curl_setopt($this->_curl, CURLOPT_INFILESIZE, $this->_config['curloptions'][CURLOPT_INFILESIZE]);
  299. unset($this->_config['curloptions'][CURLOPT_INFILE]);
  300. unset($this->_config['curloptions'][CURLOPT_INFILESIZE]);
  301. } elseif ($method == Zend_Http_Client::PUT) {
  302. // This is a PUT by a setRawData string, not by file-handle
  303. curl_setopt($this->_curl, CURLOPT_POSTFIELDS, $body);
  304. }
  305. // set additional curl options
  306. if (isset($this->_config['curloptions'])) {
  307. foreach ((array)$this->_config['curloptions'] as $k => $v) {
  308. if (!in_array($k, $this->_invalidOverwritableCurlOptions)) {
  309. if (curl_setopt($this->_curl, $k, $v) == false) {
  310. require_once 'Zend/Http/Client/Exception.php';
  311. throw new Zend_Http_Client_Exception(sprintf("Unknown or erroreous cURL option '%s' set", $k));
  312. }
  313. }
  314. }
  315. }
  316. // send the request
  317. $this->_response = curl_exec($this->_curl);
  318. $request = curl_getinfo($this->_curl, CURLINFO_HEADER_OUT);
  319. $request .= $body;
  320. if (empty($this->_response)) {
  321. require_once 'Zend/Http/Client/Exception.php';
  322. throw new Zend_Http_Client_Exception("Error in cURL request: " . curl_error($this->_curl));
  323. }
  324. // cURL automatically decodes chunked-messages, this means we have to disallow the Zend_Http_Response to do it again
  325. if (stripos($this->_response, "Transfer-Encoding: chunked\r\n")) {
  326. $this->_response = str_ireplace("Transfer-Encoding: chunked\r\n", '', $this->_response);
  327. }
  328. // Eliminate multiple HTTP responses.
  329. do {
  330. $parts = preg_split('|(?:\r?\n){2}|m', $this->_response, 2);
  331. $again = false;
  332. if (isset($parts[1]) && preg_match("|^HTTP/1\.[01](.*?)\r\n|mi", $parts[1])) {
  333. $this->_response = $parts[1];
  334. $again = true;
  335. }
  336. } while ($again);
  337. // cURL automatically handles Proxy rewrites, remove the "HTTP/1.0 200 Connection established" string:
  338. if (stripos($this->_response, "HTTP/1.0 200 Connection established\r\n\r\n") !== false) {
  339. $this->_response = str_ireplace("HTTP/1.0 200 Connection established\r\n\r\n", '', $this->_response);
  340. }
  341. return $request;
  342. }
  343. /**
  344. * Return read response from server
  345. *
  346. * @return string
  347. */
  348. public function read()
  349. {
  350. return $this->_response;
  351. }
  352. /**
  353. * Close the connection to the server
  354. *
  355. */
  356. public function close()
  357. {
  358. if(is_resource($this->_curl)) {
  359. curl_close($this->_curl);
  360. }
  361. $this->_curl = null;
  362. $this->_connected_to = array(null, null);
  363. }
  364. /**
  365. * Get cUrl Handle
  366. *
  367. * @return resource
  368. */
  369. public function getHandle()
  370. {
  371. return $this->_curl;
  372. }
  373. }