Curl.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. <?php
  2. /**
  3. * Yii2 cURL wrapper
  4. * With RESTful support.
  5. *
  6. * @category Web-yii2
  7. * @package yii2-curl
  8. * @author Nils Gajsek <info@linslin.org>
  9. * @copyright 2013-2017 Nils Gajsek <info@linslin.org>
  10. * @license http://opensource.org/licenses/MIT MIT Public
  11. * @version 1.0.11
  12. * @link http://www.linslin.org
  13. *
  14. */
  15. namespace linslin\yii2\curl;
  16. use Yii;
  17. use yii\base\Exception;
  18. use yii\helpers\Json;
  19. use yii\web\HttpException;
  20. /**
  21. * cURL class
  22. */
  23. class Curl
  24. {
  25. // ################################################ class vars // ################################################
  26. /**
  27. * @var string
  28. * Holds response data right after sending a request.
  29. */
  30. public $response = null;
  31. /**
  32. * @var null|integer
  33. * Error code holder: https://curl.haxx.se/libcurl/c/libcurl-errors.html
  34. */
  35. public $errorCode = null;
  36. /**
  37. * @var integer HTTP-Status Code
  38. * This value will hold HTTP-Status Code. False if request was not successful.
  39. */
  40. public $responseCode = null;
  41. /**
  42. * @var string|null HTTP Response Charset
  43. * (taken from Content-type header)
  44. */
  45. public $responseCharset = null;
  46. /**
  47. * @var int HTTP Response Length
  48. * (taken from Content-length header, or strlen() of downloaded content)
  49. */
  50. public $responseLength = -1;
  51. /**
  52. * @var string|null HTTP Response Content Type
  53. * (taken from Content-type header)
  54. */
  55. public $responseType = null;
  56. /**
  57. * @var array|null HTTP Response headers
  58. * Lists response header in an array if CURLOPT_HEADER is set to true.
  59. */
  60. public $responseHeaders = null;
  61. /**
  62. * @var array HTTP-Status Code
  63. * Custom options holder
  64. */
  65. private $_options = [];
  66. /**
  67. * @var resource|null
  68. * Holds cURL-Handler
  69. */
  70. private $_curl = null;
  71. /**
  72. * @var array default curl options
  73. * Default curl options
  74. */
  75. private $_defaultOptions = [
  76. CURLOPT_USERAGENT => 'Yii2-Curl-Agent',
  77. CURLOPT_TIMEOUT => 30,
  78. CURLOPT_CONNECTTIMEOUT => 30,
  79. CURLOPT_RETURNTRANSFER => true,
  80. CURLOPT_HEADER => true,
  81. ];
  82. // ############################################### class methods // ##############################################
  83. /**
  84. * Start performing GET-HTTP-Request
  85. *
  86. * @param string $url
  87. * @param boolean $raw if response body contains JSON and should be decoded
  88. *
  89. * @return mixed response
  90. */
  91. public function get($url, $raw = true)
  92. {
  93. return $this->_httpRequest('GET', $url, $raw);
  94. }
  95. /**
  96. * Start performing HEAD-HTTP-Request
  97. *
  98. * @param string $url
  99. *
  100. * @return mixed response
  101. */
  102. public function head($url)
  103. {
  104. return $this->_httpRequest('HEAD', $url);
  105. }
  106. /**
  107. * Start performing POST-HTTP-Request
  108. *
  109. * @param string $url
  110. * @param boolean $raw if response body contains JSON and should be decoded
  111. *
  112. * @return mixed response
  113. */
  114. public function post($url, $raw = true)
  115. {
  116. return $this->_httpRequest('POST', $url, $raw);
  117. }
  118. /**
  119. * Start performing PUT-HTTP-Request
  120. *
  121. * @param string $url
  122. * @param boolean $raw if response body contains JSON and should be decoded
  123. *
  124. * @return mixed response
  125. */
  126. public function put($url, $raw = true)
  127. {
  128. return $this->_httpRequest('PUT', $url, $raw);
  129. }
  130. /**
  131. * Start performing PATCH-HTTP-Request
  132. *
  133. * @param string $url
  134. * @param boolean $raw if response body contains JSON and should be decoded
  135. *
  136. * @return mixed response
  137. */
  138. public function patch($url, $raw = true)
  139. {
  140. return $this->_httpRequest('PATCH', $url, $raw);
  141. }
  142. /**
  143. * Start performing DELETE-HTTP-Request
  144. *
  145. * @param string $url
  146. * @param boolean $raw if response body contains JSON and should be decoded
  147. *
  148. * @return mixed response
  149. */
  150. public function delete($url, $raw = true)
  151. {
  152. return $this->_httpRequest('DELETE', $url, $raw);
  153. }
  154. /**
  155. * Set curl option
  156. *
  157. * @param string $key
  158. * @param mixed $value
  159. *
  160. * @return $this
  161. */
  162. public function setOption($key, $value)
  163. {
  164. //set value
  165. if (array_key_exists($key, $this->_defaultOptions) && $key !== CURLOPT_WRITEFUNCTION) {
  166. $this->_defaultOptions[$key] = $value;
  167. } else {
  168. $this->_options[$key] = $value;
  169. }
  170. //return self
  171. return $this;
  172. }
  173. /**
  174. * Set curl options
  175. *
  176. * @param array $options
  177. *
  178. * @return $this
  179. */
  180. public function setOptions($options)
  181. {
  182. $this->_options = $options + $this->_options;
  183. return $this;
  184. }
  185. /**
  186. * Unset a single curl option
  187. *
  188. * @param string $key
  189. *
  190. * @return $this
  191. */
  192. public function unsetOption($key)
  193. {
  194. //reset a single option if its set already
  195. if (isset($this->_options[$key])) {
  196. unset($this->_options[$key]);
  197. }
  198. return $this;
  199. }
  200. /**
  201. * Unset all curl option, excluding default options.
  202. *
  203. * @return $this
  204. */
  205. public function unsetOptions()
  206. {
  207. //reset all options
  208. if (isset($this->_options)) {
  209. $this->_options = [];
  210. }
  211. return $this;
  212. }
  213. /**
  214. * Total reset of options, responses, etc.
  215. *
  216. * @return $this
  217. */
  218. public function reset()
  219. {
  220. if ($this->_curl !== null) {
  221. curl_close($this->_curl); //stop curl
  222. }
  223. //reset all options
  224. if (isset($this->_options)) {
  225. $this->_options = [];
  226. }
  227. //reset response & status params
  228. $this->_curl = null;
  229. $this->errorCode = null;
  230. $this->response = null;
  231. $this->responseCode = null;
  232. $this->responseCharset = null;
  233. $this->responseLength = -1;
  234. $this->responseType = null;
  235. return $this;
  236. }
  237. /**
  238. * Return a single option
  239. *
  240. * @param string|integer $key
  241. * @return mixed|boolean
  242. */
  243. public function getOption($key)
  244. {
  245. //get merged options depends on default and user options
  246. $mergesOptions = $this->getOptions();
  247. //return value or false if key is not set.
  248. return isset($mergesOptions[$key]) ? $mergesOptions[$key] : false;
  249. }
  250. /**
  251. * Return merged curl options and keep keys!
  252. *
  253. * @return array
  254. */
  255. public function getOptions()
  256. {
  257. return $this->_options + $this->_defaultOptions;
  258. }
  259. /**
  260. * Get curl info according to http://php.net/manual/de/function.curl-getinfo.php
  261. *
  262. * @param null $opt
  263. * @return array|mixed
  264. */
  265. public function getInfo($opt = null)
  266. {
  267. if ($this->_curl !== null && $opt === null) {
  268. return curl_getinfo($this->_curl);
  269. } elseif ($this->_curl !== null && $opt !== null) {
  270. return curl_getinfo($this->_curl, $opt);
  271. } else {
  272. return [];
  273. }
  274. }
  275. /**
  276. * Performs HTTP request
  277. *
  278. * @param string $method
  279. * @param string $url
  280. * @param boolean $raw if response body contains JSON and should be decoded -> helper.
  281. *
  282. * @throws Exception if request failed
  283. *
  284. * @return mixed
  285. */
  286. private function _httpRequest($method, $url, $raw = false)
  287. {
  288. //set request type and writer function
  289. $this->setOption(CURLOPT_CUSTOMREQUEST, strtoupper($method));
  290. //check if method is head and set no body
  291. if ($method === 'HEAD') {
  292. $this->setOption(CURLOPT_NOBODY, true);
  293. $this->unsetOption(CURLOPT_WRITEFUNCTION);
  294. }
  295. //setup error reporting and profiling
  296. if (YII_DEBUG) {
  297. Yii::trace('Start sending cURL-Request: '.$url.'\n', __METHOD__);
  298. Yii::beginProfile($method.' '.$url.'#'.md5(serialize($this->getOption(CURLOPT_POSTFIELDS))), __METHOD__);
  299. }
  300. /**
  301. * proceed curl
  302. */
  303. $curlOptions = $this->getOptions();
  304. $this->_curl = curl_init($url);
  305. curl_setopt_array($this->_curl, $curlOptions);
  306. $response = curl_exec($this->_curl);
  307. //check if curl was successful
  308. if ($response === false) {
  309. //set error code
  310. $this->errorCode = curl_errno($this->_curl);
  311. switch ($this->errorCode) {
  312. // 7, 28 = timeout
  313. case 7:
  314. case 28:
  315. $this->responseCode = 'timeout';
  316. return false;
  317. break;
  318. default:
  319. return false;
  320. break;
  321. }
  322. }
  323. //extract header / body data if CURLOPT_HEADER are set to true
  324. if (isset($curlOptions[CURLOPT_HEADER]) && $curlOptions[CURLOPT_HEADER]) {
  325. $this->response = $this->_extractCurlBody($response);
  326. $this->responseHeaders = $this->_extractCurlHeaders($response);
  327. } else {
  328. $this->response = $response;
  329. }
  330. // Extract additional curl params
  331. $this->_extractAdditionalCurlParameter();
  332. //end yii debug profile
  333. if (YII_DEBUG) {
  334. Yii::endProfile($method.' '.$url .'#'.md5(serialize($this->getOption(CURLOPT_POSTFIELDS))), __METHOD__);
  335. }
  336. //check responseCode and return data/status
  337. if ($this->getOption(CURLOPT_CUSTOMREQUEST) === 'HEAD') {
  338. return true;
  339. } else {
  340. $this->response = $raw ? $this->response : Json::decode($this->response);
  341. return $this->response;
  342. }
  343. }
  344. /**
  345. * Extract additional curl params private class helper
  346. */
  347. private function _extractAdditionalCurlParameter ()
  348. {
  349. /**
  350. * retrieve response code
  351. */
  352. $this->responseCode = curl_getinfo($this->_curl, CURLINFO_HTTP_CODE);
  353. /**
  354. * try extract response type & charset.
  355. */
  356. $this->responseType = curl_getinfo($this->_curl, CURLINFO_CONTENT_TYPE);
  357. if (!is_null($this->responseType) && count(explode(';', $this->responseType)) > 1) {
  358. list($this->responseType, $possibleCharset) = explode(';', $this->responseType);
  359. //extract charset
  360. if (preg_match('~^charset=(.+?)$~', trim($possibleCharset), $matches) && isset($matches[1])) {
  361. $this->responseCharset = strtolower($matches[1]);
  362. }
  363. }
  364. /**
  365. * try extract response length
  366. */
  367. $this->responseLength = curl_getinfo($this->_curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
  368. if((int)$this->responseLength == -1) {
  369. $this->responseLength = strlen($this->response);
  370. }
  371. }
  372. /**
  373. * Extract body curl data from response
  374. *
  375. * @param string $response
  376. * @return string
  377. */
  378. private function _extractCurlBody ($response)
  379. {
  380. return substr($response, $this->getInfo(CURLINFO_HEADER_SIZE));
  381. }
  382. /**
  383. * Extract header curl data from response
  384. *
  385. * @param string $response
  386. * @return array
  387. */
  388. private function _extractCurlHeaders ($response)
  389. {
  390. //Init
  391. $headers = [];
  392. $headerText = substr($response, 0, strpos($response, "\r\n\r\n"));
  393. foreach (explode("\r\n", $headerText) as $i => $line) {
  394. if ($i === 0) {
  395. $headers['http_code'] = $line;
  396. } else {
  397. list ($key, $value) = explode(': ', $line);
  398. $headers[$key] = $value;
  399. }
  400. }
  401. return $headers;
  402. }
  403. }