Curl.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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 array $config
  104. * @return Zend_Http_Client_Adapter_Curl
  105. */
  106. public function setConfig($config = array())
  107. {
  108. if (!is_array($config)) {
  109. require_once 'Zend/Http/Client/Adapter/Exception.php';
  110. throw new Zend_Http_Client_Adapter_Exception('Http Adapter configuration expects an array, ' . gettype($config) . ' recieved.');
  111. }
  112. if(isset($config['proxy_user']) && isset($config['proxy_pass'])) {
  113. $this->setCurlOption(CURLOPT_PROXYUSERPWD, $config['proxy_user'].":".$config['proxy_pass']);
  114. unset($config['proxy_user'], $config['proxy_pass']);
  115. }
  116. foreach ($config as $k => $v) {
  117. $option = strtolower($k);
  118. switch($option) {
  119. case 'proxy_host':
  120. $this->setCurlOption(CURLOPT_PROXY, $v);
  121. break;
  122. case 'proxy_port':
  123. $this->setCurlOption(CURLOPT_PROXYPORT, $v);
  124. break;
  125. default:
  126. $this->_config[$option] = $v;
  127. break;
  128. }
  129. }
  130. return $this;
  131. }
  132. /**
  133. * Direct setter for cURL adapter related options.
  134. *
  135. * @param string|int $option
  136. * @param mixed $value
  137. * @return Zend_Http_Adapter_Curl
  138. */
  139. public function setCurlOption($option, $value)
  140. {
  141. if (!isset($this->_config['curloptions'])) {
  142. $this->_config['curloptions'] = array();
  143. }
  144. $this->_config['curloptions'][$option] = $value;
  145. return $this;
  146. }
  147. /**
  148. * Initialize curl
  149. *
  150. * @param string $host
  151. * @param int $port
  152. * @param boolean $secure
  153. * @return void
  154. * @throws Zend_Http_Client_Adapter_Exception if unable to connect
  155. */
  156. public function connect($host, $port = 80, $secure = false)
  157. {
  158. // If we're already connected, disconnect first
  159. if ($this->_curl) {
  160. $this->close();
  161. }
  162. // If we are connected to a different server or port, disconnect first
  163. if ($this->_curl
  164. && is_array($this->_connected_to)
  165. && ($this->_connected_to[0] != $host
  166. || $this->_connected_to[1] != $port)
  167. ) {
  168. $this->close();
  169. }
  170. // Do the actual connection
  171. $this->_curl = curl_init();
  172. if ($port != 80) {
  173. curl_setopt($this->_curl, CURLOPT_PORT, intval($port));
  174. }
  175. // Set timeout
  176. curl_setopt($this->_curl, CURLOPT_TIMEOUT, $this->_config['timeout']);
  177. // Set Max redirects
  178. curl_setopt($this->_curl, CURLOPT_MAXREDIRS, $this->_config['maxredirects']);
  179. if (!$this->_curl) {
  180. $this->close();
  181. require_once 'Zend/Http/Client/Adapter/Exception.php';
  182. throw new Zend_Http_Client_Adapter_Exception('Unable to Connect to ' . $host . ':' . $port);
  183. }
  184. if ($secure !== false) {
  185. // Behave the same like Zend_Http_Adapter_Socket on SSL options.
  186. if (isset($this->_config['sslcert'])) {
  187. curl_setopt($this->_curl, CURLOPT_SSLCERT, $this->_config['sslcert']);
  188. }
  189. if (isset($this->_config['sslpassphrase'])) {
  190. curl_setopt($this->_curl, CURLOPT_SSLCERTPASSWD, $this->_config['sslpassphrase']);
  191. }
  192. }
  193. // Update connected_to
  194. $this->_connected_to = array($host, $port);
  195. }
  196. /**
  197. * Send request to the remote server
  198. *
  199. * @param string $method
  200. * @param Zend_Uri_Http $uri
  201. * @param float $http_ver
  202. * @param array $headers
  203. * @param string $body
  204. * @return string $request
  205. * @throws Zend_Http_Client_Adapter_Exception If connection fails, connected to wrong host, no PUT file defined, unsupported method, or unsupported cURL option
  206. */
  207. public function write($method, $uri, $http_ver = '1.1', $headers = array(), $body = '')
  208. {
  209. // Make sure we're properly connected
  210. if (!$this->_curl) {
  211. require_once 'Zend/Http/Client/Adapter/Exception.php';
  212. throw new Zend_Http_Client_Adapter_Exception("Trying to write but we are not connected");
  213. }
  214. if ($this->_connected_to[0] != $uri->getHost() || $this->_connected_to[1] != $uri->getPort()) {
  215. require_once 'Zend/Http/Client/Adapter/Exception.php';
  216. throw new Zend_Http_Client_Adapter_Exception("Trying to write but we are connected to the wrong host");
  217. }
  218. // set URL
  219. curl_setopt($this->_curl, CURLOPT_URL, $uri->__toString());
  220. // ensure correct curl call
  221. $curlValue = true;
  222. switch ($method) {
  223. case Zend_Http_Client::GET:
  224. $curlMethod = CURLOPT_HTTPGET;
  225. break;
  226. case Zend_Http_Client::POST:
  227. $curlMethod = CURLOPT_POST;
  228. break;
  229. case Zend_Http_Client::PUT:
  230. // There are two different types of PUT request, either a Raw Data string has been set
  231. // or CURLOPT_INFILE and CURLOPT_INFILESIZE are used.
  232. if (isset($this->_config['curloptions'][CURLOPT_INFILE])) {
  233. if (!isset($this->_config['curloptions'][CURLOPT_INFILESIZE])) {
  234. require_once 'Zend/Http/Client/Adapter/Exception.php';
  235. 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.");
  236. }
  237. // Now we will probably already have Content-Length set, so that we have to delete it
  238. // from $headers at this point:
  239. foreach ($headers AS $k => $header) {
  240. if (stristr($header, "Content-Length:") !== false) {
  241. unset($headers[$k]);
  242. }
  243. }
  244. $curlMethod = CURLOPT_PUT;
  245. } else {
  246. $curlMethod = CURLOPT_CUSTOMREQUEST;
  247. $curlValue = "PUT";
  248. }
  249. break;
  250. case Zend_Http_Client::DELETE:
  251. $curlMethod = CURLOPT_CUSTOMREQUEST;
  252. $curlValue = "DELETE";
  253. break;
  254. case Zend_Http_Client::OPTIONS:
  255. $curlMethod = CURLOPT_CUSTOMREQUEST;
  256. $curlValue = "OPTIONS";
  257. break;
  258. case Zend_Http_Client::TRACE:
  259. $curlMethod = CURLOPT_CUSTOMREQUEST;
  260. $curlValue = "TRACE";
  261. break;
  262. default:
  263. // For now, through an exception for unsupported request methods
  264. require_once 'Zend/Http/Client/Adapter/Exception.php';
  265. throw new Zend_Http_Client_Adapter_Exception("Method currently not supported");
  266. }
  267. // get http version to use
  268. $curlHttp = ($http_ver = 1.1) ? CURL_HTTP_VERSION_1_1 : CURL_HTTP_VERSION_1_0;
  269. // mark as HTTP request and set HTTP method
  270. curl_setopt($this->_curl, $curlHttp, true);
  271. curl_setopt($this->_curl, $curlMethod, $curlValue);
  272. // ensure headers are also returned
  273. curl_setopt($this->_curl, CURLOPT_HEADER, true);
  274. // ensure actual response is returned
  275. curl_setopt($this->_curl, CURLOPT_RETURNTRANSFER, true);
  276. // set additional headers
  277. $headers['Accept'] = '';
  278. curl_setopt($this->_curl, CURLOPT_HTTPHEADER, $headers);
  279. /**
  280. * Make sure POSTFIELDS is set after $curlMethod is set:
  281. * @link http://de2.php.net/manual/en/function.curl-setopt.php#81161
  282. */
  283. if ($method == Zend_Http_Client::POST) {
  284. curl_setopt($this->_curl, CURLOPT_POSTFIELDS, $body);
  285. } elseif ($curlMethod == CURLOPT_PUT) {
  286. // this covers a PUT by file-handle:
  287. // Make the setting of this options explicit (rather than setting it through the loop following a bit lower)
  288. // to group common functionality together.
  289. curl_setopt($this->_curl, CURLOPT_INFILE, $this->_config['curloptions'][CURLOPT_INFILE]);
  290. curl_setopt($this->_curl, CURLOPT_INFILESIZE, $this->_config['curloptions'][CURLOPT_INFILESIZE]);
  291. unset($this->_config['curloptions'][CURLOPT_INFILE]);
  292. unset($this->_config['curloptions'][CURLOPT_INFILESIZE]);
  293. } elseif ($method == Zend_Http_Client::PUT) {
  294. // This is a PUT by a setRawData string, not by file-handle
  295. curl_setopt($this->_curl, CURLOPT_POSTFIELDS, $body);
  296. }
  297. // set additional curl options
  298. if (isset($this->_config['curloptions'])) {
  299. foreach ((array)$this->_config['curloptions'] as $k => $v) {
  300. if (!in_array($k, $this->_invalidOverwritableCurlOptions)) {
  301. if (curl_setopt($this->_curl, $k, $v) == false) {
  302. require_once 'Zend/Http/Client/Exception.php';
  303. throw new Zend_Http_Client_Exception(sprintf("Unknown or erroreous cURL option '%s' set", $k));
  304. }
  305. }
  306. }
  307. }
  308. // send the request
  309. $this->_response = curl_exec($this->_curl);
  310. $request = curl_getinfo($this->_curl, CURLINFO_HEADER_OUT);
  311. $request .= $body;
  312. if (empty($this->_response)) {
  313. require_once 'Zend/Http/Client/Exception.php';
  314. throw new Zend_Http_Client_Exception("Error in cURL request: " . curl_error($this->_curl));
  315. }
  316. // cURL automatically decodes chunked-messages, this means we have to disallow the Zend_Http_Response to do it again
  317. if (stripos($this->_response, "Transfer-Encoding: chunked\r\n")) {
  318. $this->_response = str_ireplace("Transfer-Encoding: chunked\r\n", '', $this->_response);
  319. }
  320. // Eliminate multiple HTTP responses.
  321. do {
  322. $parts = preg_split('|(?:\r?\n){2}|m', $this->_response, 2);
  323. $again = false;
  324. if (isset($parts[1]) && preg_match("|^HTTP/1\.[01](.*?)\r\n|mi", $parts[1])) {
  325. $this->_response = $parts[1];
  326. $again = true;
  327. }
  328. } while ($again);
  329. // cURL automatically handles Proxy rewrites, remove the "HTTP/1.0 200 Connection established" string:
  330. if (stripos($this->_response, "HTTP/1.0 200 Connection established\r\n\r\n") !== false) {
  331. $this->_response = str_ireplace("HTTP/1.0 200 Connection established\r\n\r\n", '', $this->_response);
  332. }
  333. return $request;
  334. }
  335. /**
  336. * Return read response from server
  337. *
  338. * @return string
  339. */
  340. public function read()
  341. {
  342. return $this->_response;
  343. }
  344. /**
  345. * Close the connection to the server
  346. *
  347. */
  348. public function close()
  349. {
  350. if(is_resource($this->_curl)) {
  351. curl_close($this->_curl);
  352. }
  353. $this->_curl = null;
  354. $this->_connected_to = array(null, null);
  355. }
  356. /**
  357. * Get cUrl Handle
  358. *
  359. * @return resource
  360. */
  361. public function getHandle()
  362. {
  363. return $this->_curl;
  364. }
  365. }