<?php
/**
* Varnish CodeIgniter utils.
*
* @author Anton Lindqvist <anton@qvister.se>
* @copyright 2010 Anton Lindqvist <anton@qvister.se>
* @license http://www.opensource.org/licenses/mit-license.php MIT
* @link https://gist.github.com/gists/727012
*/
class Varnish {
/**
* cURL default options.
*
* @access private
*
* @var array
*/
private static $_curl_default_options = array(
CURLOPT_HEADER => false,
CURLOPT_RETURNTRANSFER => true
);
/**
* cURL purge options.
*
* @access private
*
* @var array
*/
private static $_curl_purge_options = array(
CURLOPT_CUSTOMREQUEST => 'PURGE',
CURLOPT_FORBID_REUSE => true
);
/**
* Purge a given URI.
*
* @param string $uri
*
* @return boolean
* @see Varnish::_curl()
*/
function purge($uri) {
if (!preg_match('/^https?\:\/\//', $uri)) {
$uri = trim(base_url(), '/') . $uri;
}
return ($this->_curl($uri, self::$_curl_purge_options))
? true
: false;
}
/**
* Perform an HTTP request using cURL.
*
* @param string $url The URL to request
* @param array $options Optional cURL options.
*
* @return boolean
*/
private function _curl($url, $options = null) {
$ch = curl_init($url);
if (is_array($options) && count($options)) {
foreach (self::$_curl_default_options as $key => $val) {
if (!array_key_exists($key, $options)) {
$options[$key] = $val;
}
}
} else {
$options = self::$_curl_default_options;
}
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return (preg_match('/^2[0-9]{2}$/', (string)$http_code))
? $response
: false;
}
}