Curl.php 14 KB

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