source: pro-violet-viettel/www/deploy/20150304/application/libraries/Curl.php @ 803

Last change on this file since 803 was 780, checked in by dungnv, 10 years ago
File size: 10.2 KB
Line 
1<?php defined('BASEPATH') OR exit('No direct script access allowed');
2
3/**
4 * CodeIgniter Curl Class
5 *
6 * Work with remote servers via cURL much easier than using the native PHP bindings.
7 *
8 * @package             CodeIgniter
9 * @subpackage          Libraries
10 * @category            Libraries
11 * @author              Philip Sturgeon
12 * @license         http://philsturgeon.co.uk/code/dbad-license
13 * @link                        http://philsturgeon.co.uk/code/codeigniter-curl
14 */
15class Curl {
16
17        protected $_ci;                 // CodeIgniter instance
18        protected $response = '';       // Contains the cURL response for debug
19        protected $session;             // Contains the cURL handler for a session
20        protected $url;                 // URL of the session
21        protected $options = array();   // Populates curl_setopt_array
22        protected $headers = array();   // Populates extra HTTP headers
23        public $error_code;             // Error code returned as an int
24        public $error_string;           // Error message returned as a string
25        public $info;                   // Returned after request (elapsed time, etc)
26
27        function __construct($url = '')
28        {
29                $this->_ci = & get_instance();
30                log_message('debug', 'cURL Class Initialized');
31
32                if ( ! $this->is_enabled())
33                {
34                        log_message('error', 'cURL Class - PHP was not built with cURL enabled. Rebuild PHP with --with-curl to use cURL.');
35                }
36
37                $url AND $this->create($url);
38        }
39
40        public function __call($method, $arguments)
41        {
42                if (in_array($method, array('simple_get', 'simple_post', 'simple_put', 'simple_delete', 'simple_patch')))
43                {
44                        // Take off the "simple_" and past get/post/put/delete/patch to _simple_call
45                        $verb = str_replace('simple_', '', $method);
46                        array_unshift($arguments, $verb);
47                        return call_user_func_array(array($this, '_simple_call'), $arguments);
48                }
49        }
50
51        /* =================================================================================
52         * SIMPLE METHODS
53         * Using these methods you can make a quick and easy cURL call with one line.
54         * ================================================================================= */
55
56        public function _simple_call($method, $url, $params = array(), $options = array())
57        {
58                // Get acts differently, as it doesnt accept parameters in the same way
59                if ($method === 'get')
60                {
61                        // If a URL is provided, create new session
62                        $this->create($url.($params ? '?'.http_build_query($params, NULL, '&') : ''));
63                }
64
65                else
66                {
67                        // If a URL is provided, create new session
68                        $this->create($url);
69
70                        $this->{$method}($params);
71                }
72
73                // Add in the specific options provided
74                $this->options($options);
75
76                return $this->execute();
77        }
78
79        public function simple_ftp_get($url, $file_path, $username = '', $password = '')
80        {
81                // If there is no ftp:// or any protocol entered, add ftp://
82                if ( ! preg_match('!^(ftp|sftp)://! i', $url))
83                {
84                        $url = 'ftp://' . $url;
85                }
86
87                // Use an FTP login
88                if ($username != '')
89                {
90                        $auth_string = $username;
91
92                        if ($password != '')
93                        {
94                                $auth_string .= ':' . $password;
95                        }
96
97                        // Add the user auth string after the protocol
98                        $url = str_replace('://', '://' . $auth_string . '@', $url);
99                }
100
101                // Add the filepath
102                $url .= $file_path;
103
104                $this->option(CURLOPT_BINARYTRANSFER, TRUE);
105                $this->option(CURLOPT_VERBOSE, TRUE);
106
107                return $this->execute();
108        }
109
110        /* =================================================================================
111         * ADVANCED METHODS
112         * Use these methods to build up more complex queries
113         * ================================================================================= */
114
115        public function post($params = array(), $options = array())
116        {
117                // If its an array (instead of a query string) then format it correctly
118                if (is_array($params))
119                {
120                        $params = http_build_query($params, NULL, '&');
121                }
122
123                // Add in the specific options provided
124                $this->options($options);
125
126                $this->http_method('post');
127
128                $this->option(CURLOPT_POST, TRUE);
129                $this->option(CURLOPT_POSTFIELDS, $params);
130        }
131
132        public function put($params = array(), $options = array())
133        {
134                // If its an array (instead of a query string) then format it correctly
135                if (is_array($params))
136                {
137                        $params = http_build_query($params, NULL, '&');
138                }
139
140                // Add in the specific options provided
141                $this->options($options);
142
143                $this->http_method('put');
144                $this->option(CURLOPT_POSTFIELDS, $params);
145
146                // Override method, I think this overrides $_POST with PUT data but... we'll see eh?
147                $this->option(CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: PUT'));
148        }
149
150        public function patch($params = array(), $options = array())
151        {
152                // If its an array (instead of a query string) then format it correctly
153                if (is_array($params))
154                {
155                        $params = http_build_query($params, NULL, '&');
156                }
157
158                // Add in the specific options provided
159                $this->options($options);
160
161                $this->http_method('patch');
162                $this->option(CURLOPT_POSTFIELDS, $params);
163
164                // Override method, I think this overrides $_POST with PATCH data but... we'll see eh?
165                $this->option(CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: PATCH'));
166        }
167
168        public function delete($params, $options = array())
169        {
170                // If its an array (instead of a query string) then format it correctly
171                if (is_array($params))
172                {
173                        $params = http_build_query($params, NULL, '&');
174                }
175
176                // Add in the specific options provided
177                $this->options($options);
178
179                $this->http_method('delete');
180
181                $this->option(CURLOPT_POSTFIELDS, $params);
182        }
183
184        public function set_cookies($params = array())
185        {
186                if (is_array($params))
187                {
188                        $params = http_build_query($params, NULL, '&');
189                }
190
191                $this->option(CURLOPT_COOKIE, $params);
192                return $this;
193        }
194
195        public function http_header($header, $content = NULL)
196        {
197                $this->headers[] = $content ? $header . ': ' . $content : $header;
198                return $this;
199        }
200
201        public function http_method($method)
202        {
203                $this->options[CURLOPT_CUSTOMREQUEST] = strtoupper($method);
204                return $this;
205        }
206
207        public function http_login($username = '', $password = '', $type = 'any')
208        {
209                $this->option(CURLOPT_HTTPAUTH, constant('CURLAUTH_' . strtoupper($type)));
210                $this->option(CURLOPT_USERPWD, $username . ':' . $password);
211                return $this;
212        }
213
214        public function proxy($url = '', $port = 80)
215        {
216                $this->option(CURLOPT_HTTPPROXYTUNNEL, TRUE);
217                $this->option(CURLOPT_PROXY, $url . ':' . $port);
218                return $this;
219        }
220
221        public function proxy_login($username = '', $password = '')
222        {
223                $this->option(CURLOPT_PROXYUSERPWD, $username . ':' . $password);
224                return $this;
225        }
226
227        public function ssl($verify_peer = TRUE, $verify_host = 2, $path_to_cert = NULL)
228        {
229                if ($verify_peer)
230                {
231                        $this->option(CURLOPT_SSL_VERIFYPEER, TRUE);
232                        $this->option(CURLOPT_SSL_VERIFYHOST, $verify_host);
233                        if (isset($path_to_cert)) {
234                                $path_to_cert = realpath($path_to_cert);
235                                $this->option(CURLOPT_CAINFO, $path_to_cert);
236                        }
237                }
238                else
239                {
240                        $this->option(CURLOPT_SSL_VERIFYPEER, FALSE);
241                        $this->option(CURLOPT_SSL_VERIFYHOST, $verify_host);
242                }
243                return $this;
244        }
245
246        public function options($options = array())
247        {
248                // Merge options in with the rest - done as array_merge() does not overwrite numeric keys
249                foreach ($options as $option_code => $option_value)
250                {
251                        $this->option($option_code, $option_value);
252                }
253
254                // Set all options provided
255                curl_setopt_array($this->session, $this->options);
256
257                return $this;
258        }
259
260        public function option($code, $value, $prefix = 'opt')
261        {
262                if (is_string($code) && !is_numeric($code))
263                {
264                        $code = constant('CURL' . strtoupper($prefix) . '_' . strtoupper($code));
265                }
266
267                $this->options[$code] = $value;
268                return $this;
269        }
270
271        // Start a session from a URL
272        public function create($url)
273        {
274                // If no a protocol in URL, assume its a CI link
275                if ( ! preg_match('!^\w+://! i', $url))
276                {
277                        $this->_ci->load->helper('url');
278                        $url = site_url($url);
279                }
280
281                $this->url = $url;
282                $this->session = curl_init($this->url);
283
284                return $this;
285        }
286
287        // End a session and return the results
288        public function execute()
289        {
290                // Set two default options, and merge any extra ones in
291                if ( ! isset($this->options[CURLOPT_TIMEOUT]))
292                {
293                        $this->options[CURLOPT_TIMEOUT] = 30;
294                }
295                if ( ! isset($this->options[CURLOPT_RETURNTRANSFER]))
296                {
297                        $this->options[CURLOPT_RETURNTRANSFER] = TRUE;
298                }
299                if ( ! isset($this->options[CURLOPT_FAILONERROR]))
300                {
301                        $this->options[CURLOPT_FAILONERROR] = TRUE;
302                }
303
304                // Only set follow location if not running securely
305                if ( ! ini_get('safe_mode') && ! ini_get('open_basedir'))
306                {
307                        // Ok, follow location is not set already so lets set it to true
308                        if ( ! isset($this->options[CURLOPT_FOLLOWLOCATION]))
309                        {
310                                $this->options[CURLOPT_FOLLOWLOCATION] = TRUE;
311                        }
312                }
313
314                if ( ! empty($this->headers))
315                {
316                        $this->option(CURLOPT_HTTPHEADER, $this->headers);
317                }
318
319                $this->options();
320
321                // Execute the request & and hide all output
322                $this->response = curl_exec($this->session);
323                $this->info = curl_getinfo($this->session);
324
325                // Request failed
326                if ($this->response === FALSE)
327                {
328                        $errno = curl_errno($this->session);
329                        $error = curl_error($this->session);
330
331                        curl_close($this->session);
332                        $this->set_defaults();
333
334                        $this->error_code = $errno;
335                        $this->error_string = $error;
336
337                        return FALSE;
338                }
339
340                // Request successful
341                else
342                {
343                        curl_close($this->session);
344                        $this->last_response = $this->response;
345                        $this->set_defaults();
346                        return $this->last_response;
347                }
348        }
349
350        public function is_enabled()
351        {
352                return function_exists('curl_init');
353        }
354
355        public function debug()
356        {
357                echo "=============================================<br/>\n";
358                echo "<h2>CURL Test</h2>\n";
359                echo "=============================================<br/>\n";
360                echo "<h3>Response</h3>\n";
361                echo "<code>" . nl2br(htmlentities($this->last_response)) . "</code><br/>\n\n";
362
363                if ($this->error_string)
364                {
365                        echo "=============================================<br/>\n";
366                        echo "<h3>Errors</h3>";
367                        echo "<strong>Code:</strong> " . $this->error_code . "<br/>\n";
368                        echo "<strong>Message:</strong> " . $this->error_string . "<br/>\n";
369                }
370
371                echo "=============================================<br/>\n";
372                echo "<h3>Info</h3>";
373                echo "<pre>";
374                print_r($this->info);
375                echo "</pre>";
376        }
377
378        public function debug_request()
379        {
380                return array(
381                        'url' => $this->url
382                );
383        }
384
385        public function set_defaults()
386        {
387                $this->response = '';
388                $this->headers = array();
389                $this->options = array();
390                $this->error_code = NULL;
391                $this->error_string = '';
392                $this->session = NULL;
393        }
394
395}
396
397/* End of file Curl.php */
398/* Location: ./application/libraries/Curl.php */
Note: See TracBrowser for help on using the repository browser.