PageRenderTime 48ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/class/curl.php

https://gitlab.com/afdallah/myongkir
PHP | 356 lines | 241 code | 67 blank | 48 comment | 25 complexity | 1efde6dab0b1e740f9abfe5d7b8b04f6 MD5 | raw file
  1. <?php
  2. /**
  3. * CodeIgniter REST Class
  4. *
  5. * Make REST requests to RESTful services with simple syntax.
  6. *
  7. * @package CodeIgniter
  8. * @subpackage Libraries
  9. * @category Libraries
  10. * @author Philip Sturgeon
  11. * @license http://philsturgeon.co.uk/code/dbad-license
  12. * @link http://github.com/philsturgeon/codeigniter-restclient
  13. *
  14. */
  15. if ( ! defined( 'ABSPATH' ) ) {
  16. exit;
  17. }
  18. class Curl {
  19. private $response; // Contains the cURL response for debug
  20. private $session; // Contains the cURL handler for a session
  21. private $url; // URL of the session
  22. private $options = array(); // Populates curl_setopt_array
  23. private $headers = array(); // Populates extra HTTP headers
  24. public $error_code; // Error code returned as an int
  25. public $error_string; // Error message returned as a string
  26. public $info; // Returned after request (elapsed time, etc)
  27. function __construct($url = '')
  28. {
  29. if ( ! $this->is_enabled())
  30. {
  31. echo 'cURL not enabled.';
  32. }
  33. $url AND $this->create($url);
  34. }
  35. function __call($method, $arguments)
  36. {
  37. if (in_array($method, array('simple_get', 'simple_post', 'simple_put', 'simple_delete')))
  38. {
  39. // Take off the "simple_" and past get/post/put/delete to _simple_call
  40. $verb = str_replace('simple_', '', $method);
  41. array_unshift($arguments, $verb);
  42. return call_user_func_array(array($this, '_simple_call'), $arguments);
  43. }
  44. }
  45. /* =================================================================================
  46. * SIMPLE METHODS
  47. * Using these methods you can make a quick and easy cURL call with one line.
  48. * ================================================================================= */
  49. // Return a get request results
  50. public function _simple_call($method, $url, $params = array(), $options = array())
  51. {
  52. // If a URL is provided, create new session
  53. $this->create($url);
  54. $this->{$method}($params, $options);
  55. // Add in the specific options provided
  56. $this->options($options);
  57. return $this->execute();
  58. }
  59. public function simple_ftp_get($url, $file_path, $username = '', $password = '')
  60. {
  61. // If there is no ftp:// or any protocol entered, add ftp://
  62. if ( ! preg_match('!^(ftp|sftp)://! i', $url))
  63. {
  64. $url = 'ftp://'.$url;
  65. }
  66. // Use an FTP login
  67. if ($username != '')
  68. {
  69. $auth_string = $username;
  70. if ($password != '')
  71. {
  72. $auth_string .= ':'.$password;
  73. }
  74. // Add the user auth string after the protocol
  75. $url = str_replace('://', '://'.$auth_string.'@', $url);
  76. }
  77. // Add the filepath
  78. $url .= $file_path;
  79. $this->option(CURLOPT_BINARYTRANSFER, TRUE);
  80. $this->option(CURLOPT_VERBOSE, TRUE);
  81. return $this->execute();
  82. }
  83. /* =================================================================================
  84. * ADVANCED METHODS
  85. * Use these methods to build up more complex queries
  86. * ================================================================================= */
  87. public function post($params = array(), $options = array())
  88. {
  89. // If its an array (instead of a query string) then format it correctly
  90. if (is_array($params))
  91. {
  92. $params = http_build_query($params, NULL, '&');
  93. }
  94. // Add in the specific options provided
  95. $this->options($options);
  96. $this->http_method('post');
  97. $this->option(CURLOPT_POST, TRUE);
  98. $this->option(CURLOPT_POSTFIELDS, $params);
  99. }
  100. public function put($params = array(), $options = array())
  101. {
  102. // If its an array (instead of a query string) then format it correctly
  103. if (is_array($params))
  104. {
  105. $params = http_build_query($params, NULL, '&');
  106. }
  107. // Add in the specific options provided
  108. $this->options($options);
  109. $this->http_method('put');
  110. $this->option(CURLOPT_POSTFIELDS, $params);
  111. // Override method, I think this overrides $_POST with PUT data but... we'll see eh?
  112. $this->option(CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: PUT'));
  113. }
  114. public function delete($params, $options = array())
  115. {
  116. // If its an array (instead of a query string) then format it correctly
  117. if (is_array($params))
  118. {
  119. $params = http_build_query($params, NULL, '&');
  120. }
  121. // Add in the specific options provided
  122. $this->options($options);
  123. $this->http_method('delete');
  124. $this->option(CURLOPT_POSTFIELDS, $params);
  125. }
  126. public function set_cookies($params = array())
  127. {
  128. if (is_array($params))
  129. {
  130. $params = http_build_query($params, NULL, '&');
  131. }
  132. $this->option(CURLOPT_COOKIE, $params);
  133. return $this;
  134. }
  135. public function http_header($header, $content = NULL)
  136. {
  137. $this->headers[] = $content ? $header.': '.$content : $header;
  138. }
  139. public function http_method($method)
  140. {
  141. $this->options[CURLOPT_CUSTOMREQUEST] = strtoupper($method);
  142. return $this;
  143. }
  144. public function http_login($username = '', $password = '', $type = 'any')
  145. {
  146. $this->option(CURLOPT_HTTPAUTH, constant('CURLAUTH_'.strtoupper($type) ));
  147. $this->option(CURLOPT_USERPWD, $username.':'.$password);
  148. return $this;
  149. }
  150. public function proxy($url = '', $port = 80)
  151. {
  152. $this->option(CURLOPT_HTTPPROXYTUNNEL, TRUE);
  153. $this->option(CURLOPT_PROXY, $url.':'. $port);
  154. return $this;
  155. }
  156. public function proxy_login($username = '', $password = '')
  157. {
  158. $this->option(CURLOPT_PROXYUSERPWD, $username.':'.$password);
  159. return $this;
  160. }
  161. public function ssl( $verify_peer = TRUE, $verify_host = 2, $path_to_cert = NULL) {
  162. if ($verify_peer)
  163. {
  164. $this->option(CURLOPT_SSL_VERIFYPEER, TRUE);
  165. $this->option(CURLOPT_SSL_VERIFYHOST, $verify_host);
  166. $this->option(CURLOPT_CAINFO, $path_to_cert);
  167. }
  168. else
  169. {
  170. $this->option(CURLOPT_SSL_VERIFYPEER, FALSE);
  171. }
  172. return $this;
  173. }
  174. public function options($options = array())
  175. {
  176. // Merge options in with the rest - done as array_merge() does not overwrite numeric keys
  177. foreach($options as $option_code => $option_value)
  178. {
  179. $this->option($option_code, $option_value);
  180. }
  181. // Set all options provided
  182. curl_setopt_array($this->session, $this->options);
  183. return $this;
  184. }
  185. public function option($code, $value)
  186. {
  187. if (is_string($code) && !is_numeric($code))
  188. {
  189. $code = constant('CURLOPT_' . strtoupper($code));
  190. }
  191. $this->options[$code] = $value;
  192. return $this;
  193. }
  194. // Start a session from a URL
  195. public function create($url)
  196. {
  197. // Reset the class
  198. $this->set_defaults();
  199. // If no a protocol in URL, assume its a CI link
  200. if ( ! preg_match('!^\w+://! i', $url))
  201. {
  202. $this->load->helper('url');
  203. $url = site_url($url);
  204. }
  205. $this->url = $url;
  206. $this->session = curl_init($this->url);
  207. return $this;
  208. }
  209. // End a session and return the results
  210. public function execute()
  211. {
  212. // Set two default options, and merge any extra ones in
  213. if (!isset($this->options[CURLOPT_TIMEOUT])) $this->options[CURLOPT_TIMEOUT] = 30;
  214. if (!isset($this->options[CURLOPT_RETURNTRANSFER])) $this->options[CURLOPT_RETURNTRANSFER] = TRUE;
  215. if (!isset($this->options[CURLOPT_FAILONERROR])) $this->options[CURLOPT_FAILONERROR] = TRUE;
  216. // Only set follow location if not running securely
  217. if ( ! ini_get('safe_mode') && ! ini_get('open_basedir'))
  218. {
  219. // Ok, follow location is not set already so lets set it to true
  220. if (!isset($this->options[CURLOPT_FOLLOWLOCATION]))
  221. {
  222. $this->options[CURLOPT_FOLLOWLOCATION] = TRUE;
  223. }
  224. }
  225. if ( ! empty($this->headers))
  226. {
  227. $this->option(CURLOPT_HTTPHEADER, $this->headers);
  228. }
  229. $this->options();
  230. // Execute the request & and hide all output
  231. $this->response = curl_exec($this->session);
  232. // Request failed
  233. if ($this->response === FALSE)
  234. {
  235. $this->error_code = curl_errno($this->session);
  236. $this->error_string = curl_error($this->session);
  237. curl_close($this->session);
  238. $this->session = NULL;
  239. return FALSE;
  240. }
  241. // Request successful
  242. else
  243. {
  244. $this->info = curl_getinfo($this->session);
  245. curl_close($this->session);
  246. $this->session = NULL;
  247. return $this->response;
  248. }
  249. }
  250. public function is_enabled()
  251. {
  252. return function_exists('curl_init');
  253. }
  254. public function debug()
  255. {
  256. echo "=============================================<br/>\n";
  257. echo "<h2>CURL Test</h2>\n";
  258. echo "=============================================<br/>\n";
  259. echo "<h3>response</h3>\n";
  260. echo "<code>".nl2br(htmlentities($this->response))."</code><br/>\n\n";
  261. if ($this->error_string)
  262. {
  263. echo "=============================================<br/>\n";
  264. echo "<h3>Errors</h3>";
  265. echo "<strong>Code:</strong> ".$this->error_code."<br/>\n";
  266. echo "<strong>Message:</strong> ".$this->error_string."<br/>\n";
  267. }
  268. echo "=============================================<br/>\n";
  269. echo "<h3>Info</h3>";
  270. echo "<pre>";
  271. print_r($this->info);
  272. echo "</pre>";
  273. }
  274. public function debug_request()
  275. {
  276. return array(
  277. 'url' => $this->url,
  278. 'params' => $this->options
  279. );
  280. }
  281. private function set_defaults()
  282. {
  283. $this->response = '';
  284. $this->info = array();
  285. $this->options = array();
  286. $this->error_code = 0;
  287. $this->error_string = '';
  288. }
  289. }