A Simple Generic PHP cURL Class

A Simple Generic PHP cURL Class

cURL is a most excellent library that enables you to communicate across a network with a number of protocols. PHP integrated the cURL library early in its development and nowadays its use is widespread across countless applications. To read more about it you can visit the author’s home page, Daniel Steinberg.

I use a very short generic class that can deal with the majority of my network requests, which is available to you below.

class curl {

	static $hndl; // Handle
	static $b = ''; // Response body
	static $h = ''; // Response head
	static $i = array();
	
	static function head($ch,$data) {
		curl::$h .= $data;
		return strlen($data);
	}
	
	static function body($ch,$data) {
		curl::$b .= $data;
		return strlen($data);
	}
	
	static function fetch($url,$opts = array()) {
		curl::$h = curl::$b = '';
		curl::$i = array();
		curl::$hndl = curl_init($url);
		curl_setopt_array(curl::$hndl,$opts);
		curl_exec(curl::$hndl);
		curl::$i = curl_getinfo(curl::$hndl);
		curl_close(curl::$hndl);
	}
}

An example request and output is shown below.

curl::fetch('http://www.google.com/',array(
	CURLOPT_USERAGENT=>'Mozilla 6.0',
	CURLOPT_ENCODING=>'gzip,deflate',
	CURLOPT_TIMEOUT=>5,
	CURLOPT_HEADERFUNCTION=>array('curl','head'),
	CURLOPT_WRITEFUNCTION=>array('curl','body')
));
print_r(curl::$i);
print_r(curl::$h);
print_r(curl::$b);

Much of the magic in this generic class happens in the curl_setopt_array() function call, which sets the options described on this page. cURL pretty much covers all angles, hence the huge list of options you can pass to your request.

There is also the option of performing multiple requests should you require, which is slightly more efficient.

The nice thing about using cURL for network requests is that there is a huge amount of documentation, and the author continues to provide assistance on various forums and sites to this day.

whoami
Stefan Pejcic
Join the discussion

I enjoy constructive responses and professional comments to my posts, and invite anyone to comment or link to my site.