Curl.php 16 KB

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