Whiz: Simple cURL PHP wrapper class
I worked on a project where i needed to handle a lot with cURL request. At first i tried to use Zend_Http_Client, but it was too limited for my purpose. So i wrote my own cURL handler php class.
I tried to keep the class as simple as possible, but it should be universal and powerfull enough for easy handling. Some ideas i had before writing code:
Thoughts
- Methods should be named like the curl_* PHP functions
- Using CURL* constants and values directly
- External access to the handle
- curl_multi_* possible
- Straight forward, no extra logic where possible
- Using all curl_* functions available
Code
You can find the code on github;
https://github.com/JuliusBeckmann/Whiz-Framework/blob/master/Whiz/Http/Client/Curl.php
License is new BSD.
Examples
Instead of explaining the code now, i just give a example using as much methods possible:
// cURL options can be found here:
// http://php.net/manual/en/function.curl-setopt.php
require_once('Whiz/Http/Client/Curl.php');
// Set cURL options via constructor
$curl = new Whiz_Http_Client_Curl(
array(CURLOPT_REFERER => 'http://www.google.com/')
);
// Set URL via method (This is just to make things easier)
$curl->setUrl('http://juliusbeckmann.de/');
// $curl->exec('http://juliusbeckmann.de/'); would be also possible
// Set cURL options via method
$curl->setOption(CURLOPT_TIMEOUT, 10);
// Do the request
$curl->exec();
if($curl->isError()) {
// Error
var_dump($curl->getErrNo());
var_dump($curl->getError());
}else{
// Success
echo $curl->getResult();
// More info about the transfer
// var_dump($curl->getInfo());
// var_dump($curl->getHeader());
// var_dump($curl->getVersion());
}
// Close cURL
$curl->close();
?>
Advanced examples
And some more advanced example code:
require_once('Whiz/Http/Client/Curl.php');
// Creating a "template" class by overwriting internal config
class My_Curl extends Whiz_Http_Client_Curl {
protected $_config = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_REFERER => 'http://www.google.com/'
);
}
$curl = new My_Curl();
$curl->setUrl('http://juliusbeckmann.de/');
// Fetch configured handle
$ch = $curl->getHandle();
// Fetch a copy of the configured handle
// $ch2 = $curl->copyHandle();
// Do with handle what ever you like
// ...
$result = curl_exec($ch);
// Put handle and result back in
$curl->setFromHandle($ch, $result);
// Fetch transfer info
if($curl->isError()) {
// Error
var_dump($curl->getErrNo());
var_dump($curl->getError());
}else{
// Success
echo $curl->getResult();
// More info about the transfer
// var_dump($curl->getInfo());
// var_dump($curl->getHeader());
// var_dump($curl->getVersion());
}
// Close cURL
$curl->close();
?>