Note: Curl.php was originally written for a CodeIgniter application; however, the code will stand on its own. Furthermore, if you do not wish to use the generator class, simply remove the Curl class definition and rename Curl_Worker to Curl, and use the new Curl class directly.
The Curl
class defined in Curl.php and loaded with $CI->load->library("curl")
is just a wrapper to return new Curl_Worker
s using $CI->curl->get()
. The Curl_Worker does all the heavy lifting.
$this->load->library("curl");
$curl = $this->curl->get(); // or $curl = new Curl_Worker();
$curl->set_url("http://some.endpoint/action");
// URL can also be set in $curl = $this->curl->get("url") or $curl = new Curl_Worker("url")
$data = $curl->exec();
if($curl->status() != 200) {
die("Something is wrong!");
}
By default, CURLOPT_RETURNTRANSFER
is set to true
. This can be overridden by calling set_return(false)
. Any of the CURLOPT_XXXX
options can be set via $curl_worker->set_xxxx
, where xxxx
is the lowercase version of the last part of the CURLOPT_XXXX
constant (so, for example, $curl_worker->set_post(true)
is the same as $curl_worker->set_opt(CURLOPT_POST, true)
).
After exec()
is called, you may call status()
on the worker to get the HTTP status code returned during the request. status()
will return null
if there isn’t a status (e.g., the cURL request hasn’t been executed yet). You may also pass true
as an optional parameter to exec()
to return the data and status together in an array:
$this->load->library("curl");
$curl = $this->curl->get(); // or $curl = new Curl_Worker();
$curl->set_url("http://some.endpoint/action");
$data = $curl->exec(true);
$real_data = $data['data'];
$http_code = $data['status'];
If necessary, a Curl_Worker can be reused by resetting it via its reset()
method; however, if using the library in CodeIgniter classes, it it just as well to get a new one via $this->curl->get()
.