Skip to content

Instantly share code, notes, and snippets.

@icyleaf
Created March 31, 2010 03:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save icyleaf/349893 to your computer and use it in GitHub Desktop.
Save icyleaf/349893 to your computer and use it in GitHub Desktop.
HTTP Request/Response Library
<?php
/**
* Provides remote server communications options using [curl][ref-curl].
*
* [ref-curl]: http://php.net/curl
*
* @author icyleaf <icyleaf.cn@gmail.com>
* @link http://icyleaf.com
* @version 0.3.1
* @license http://www.opensource.org/licenses/bsd-license.php
*
* Base on Curl Library by Matt Wells (www.ninjapenguin.co.uk)
*/
class Remote {
private $_config = array();
private $_resource = NULL;
private static $_status = NULL;
/**
* Factory Method
*
* @param string $data
* @chainable
*/
public static function factory($data = array())
{
return new Remote($data);
}
/**
* Constructor
*
* @param array curl data
*/
public function __construct($data = array())
{
if( ! function_exists('curl_init'))
{
throw new Exception('A cURL error occurred. It appears you do not have cURL installed!');
}
$config = array(
CURLOPT_HEADER => FALSE
);
//Apply any passed configuration
$data += $config;
$this->_config = $data;
$this->_resource = curl_init();
//Apply configuration settings
foreach ($this->_config as $key => $value)
{
$this->set_opt($key, $value);
}
}
/**
* Set option
*
* @param string Curl option to set
* @param string Value for option
* @chainable
*/
public function set_opt($key, $value)
{
curl_setopt($this->_resource, $key, $value);
return $this;
}
/**
* Execute the curl request and return the response
*
* @return string Returned output from the requested resource
* @throws Kohana_User_Exception
*/
public function exec()
{
$ret = curl_exec($this->_resource);
//Wrap the error reporting in an exception
if($ret === FALSE)
{
throw new Exception('Curl Error: ' . curl_error($this->_resource));
}
else
{
Remote::$_status = curl_getinfo($this->_resource, CURLINFO_HTTP_CODE);
return $ret;
}
}
/**
* Get curl Error
*
* @return string any current error for the curl request
*/
public function get_error()
{
return curl_error($this->_resource);
}
/**
* Destructor
*/
function __destruct()
{
curl_close($this->_resource);
}
/**
* Request GET method
* Execute an HTTP GET request using curl
*
* @param string url to request
* @param array additional headers to send in the request
* @param boolean flag to return only the headers
* @param array Additional curl options to instantiate curl with
*/
public static function get($url, $data = NULL, Array $headers = array(), $headers_only = FALSE, Array $curl_options = array())
{
if (is_array($data))
{
$parse = parse_url($url);
$url .= empty($parse['query']) ? '?' : '&';
$url .= http_build_query($data, '&');
}
return Remote::request('GET', $url, NULL, $headers, $headers_only, $curl_options);
}
/**
* Request POST method
* Execute an HTTP POST request using curl
*
* @param string url to request
* @param mixed past data to post to $url
* @param array additional headers to send in the request
* @param boolean flag to return only the headers
* @param array Additional curl options to instantiate curl with
*/
public static function post($url, $data = NULL, Array $headers = array(), $headers_only = FALSE, Array $curl_options = array())
{
return Remote::request('POST', $url, $data, $headers, $headers_only, $curl_options);
}
/**
* Request PUT method
* Execute an HTTP PUT request using curl
*
* @param string url to request
* @param array additional headers to send in the request
* @param boolean flag to return only the headers
* @param array Additional curl options to instantiate curl with
*/
public static function put($url, $data = NULL, Array $headers = array(), $headers_only = FALSE, Array $curl_options = array())
{
return Remote::request('PUT', $url, $data, $headers, $headers_only, $curl_options);
}
/**
* Request DELETE method
* Execute an HTTP DELETE request using curl
*
* @param string url to request
* @param array additional headers to send in the request
* @param boolean flag to return only the headers
* @param array Additional curl options to instantiate curl with
*/
public static function delete($url, $data = NULL, Array $headers = array(), $headers_only = FALSE, Array $curl_options = array())
{
return Remote::request('DELETE', $url, $data, $headers, $headers_only, $curl_options);
}
/**
* Execute an HTTP request
*
* @param string request method
* @param string url to request
* @param string additional headers to send in the request
* @param boolean flag to return only the headers
* @param array flag to return only the headers
*/
private static function request($method, $url, $data = NULL, Array $headers = array(), $headers_only = FALSE, Array $curl_options = array())
{
$ch = Remote::factory($curl_options);
$ch->set_opt(CURLOPT_URL, $url)
->set_opt(CURLOPT_RETURNTRANSFER, TRUE)
->set_opt(CURLOPT_NOBODY, $headers_only);
// Available methods: GET, POST, PUT, DELETE
$method = strtoupper($method);
switch ($method)
{
default:
case 'GET':
break;
case 'POST':
$ch->set_opt(CURLOPT_POST, TRUE)->set_opt(CURLOPT_POSTFIELDS, $data);
break;
case 'PUT':
$ch->set_opt(CURLOPT_CUSTOMREQUEST, 'PUT')->set_opt(CURLOPT_POSTFIELDS, $data);
break;
case 'DELETE':
$ch->set_opt(CURLOPT_CUSTOMREQUEST, 'DELETE');
break;
}
//Set any additional headers
if( ! empty($headers))
{
$ch->set_opt(CURLOPT_HTTPHEADER, $headers);
}
$response = array
(
'url' => $url,
'method' => $method,
'params' => $data,
'content' => $ch->exec(),
'status' => Remote::$_status,
);
return new Remote_Response($response);
}
}
/**
* Remote Response
*
* @author icyleaf <icyleaf.cn@gmail.com>
* @link http://icyleaf.com
* @version 0.2.1
* @license http://www.opensource.org/licenses/bsd-license.php
*/
class Remote_Response {
private $_url;
private $_method;
private $_params;
private $_content;
private $_status;
public function __construct($response)
{
$this->_url = $response['url'];
$this->_method = $response['method'];
$this->_params = $response['params'];
$this->_content = $response['content'];
$this->_status = $response['status'];
}
/**
* Orgin format content
*
* @return object
*/
public function to_normal()
{
return $this->_content;
}
/**
* Format String(url) to Array
*
* @param string $url
* @return array
*/
public function to_array()
{
$content = preg_replace('/&(?!(?:#\d++|[a-z]++);)/ui', '&amp;', $this->_content);
if ( ! preg_match('/[=|&amp;]/', $content))
{
return unserialize($this->_content);
}
$array = array();
$expression = explode('&amp;', $content);
for ($i = 0; $i < count($expression); $i++)
{
$attribute = explode('=', $expression[$i]);
$array[$attribute[0]] = $attribute[1];
}
return $array;
}
/**
* Format to xml
*
* @return object
*/
public function to_xml()
{
return new SimpleXMLElement($this->_content);
}
/**
* Format to json
*
* @param string $assoc
* @return mixed
*/
public function to_json($assoc = TRUE)
{
return json_decode($this->_content, $assoc);
}
public function __call($name, $arguments)
{
if ( empty($arguments) )
{
if ($name == 'status')
{
return (int) $this->_status;
}
elseif (in_array($name, array('url', 'method', 'params')))
{
return $this->{'_'.$name};
}
}
else
{
return NULL;
}
}
/**
* Default render string
*
* @return string
*/
public function __toString()
{
return $this->to_normal();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment