Curl.php 17 KB

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