Friday, May 7, 2010

1:01 AM

This class is designed to provide quick http reqest method to access external website. A CURL alternative to php native file_get_contents method. It can work without any configuration and can be called anywhere is your application using singleton design pattern. 

Unlike other Http client class in php, this is lightweight, simple and easy to use and configure. If you need more functionality you can extend the class. CURL request is fully customizable through setCurlOptions() method.
This class is suitable for those project which is not built on a PHP Framework. Usually all frameworks provide a built in Http Client Object.
Features:
- General purpose http request class.
- Supports GET & POST request Method.
- For GET Request both CURL & PHP native file_get_contents are available.
- By default CURL is used for GET Request.
- Easily configurable & can work without any configuration.
- Simple & Easy to use from anywhere in your application with a single line of code.
- Request through CURL fully configurable with all possible curl options, so it’s up to you.
- Encode given URL Automatically, may be disabled.
- Supports POST requests with a user defined array or serialised string of form values.
- Supports GET requests with a user defined parameter array.
- Support Singleton pattern
- Support Custom CURL request, may be used to extends functionality.
- Light Weight

Methods Available (This class provides):
- get()
- post()
- curlExecute()
- encodeUrl()

Class:
File: rayhttp.php
<?php
/* SVN FILE: $Id: rayhttp.php 113 2008-06-15 04:30:19Z rayhan $ */
/** * HTTP Client Class. *
ed for php developer. * - CURL * - Native php me
* A basic HTTP Client desin
gthod * * PHP Version 5 * *
08, Md. Rayhan Chowdhury * @package raynux * @subpack
* @copyright Copyright 2006-2
0age raynux.lab.http * @since version 1.0 * @version $Revision: 113 $
10:30:19 +0600 (Sun, 15 Jun 2008) $ * @a
* @modifiedby $LastChangedBy: rayhan $ * @lastModified $Date: 2008-06-15
uthor $Author: rayhan $ * @url $HeadURL: http://localhost/svn/raynux/trunk/labs/rayhttp.php $
ent desinged for php develo
* @website www.raynux.com * @license GPL */ /** * HTTP Client Class. * * A basic HTTP Cl
iper. * - CURL * - Native php method * * * @todo add utf-8 conversion. * @todo add plugins functionality * *
ry */ class RayHt
* @package raynux * @subpackage raynux.lab.http * @version 1.0 * @since version 1.0 * @author Md. Rayhan Chowdh
utp{ /** * Hold runtime instance of self * * @var array of self instances * @access private * @static */
tected $_curlInstance = null
static private $__instances; /** * Curl Instance * * @var object Curl instance * @access protected */ pr
o; /** * Default configuration for the crawler. * * @var array * @access private */ private $__defaultConfigs = array(
CURLOPT_SSL_VERIFYPEER
'client' => 'curl', 'encodeUrl' => true, 'curlOptions' => array(
=> 0, CURLOPT_RETURNTRANSFER => 1, CURLOPT_FOLLOWLOCATION => 1, CURLOPT_ENCODING => "",
CURLOPT_COOKIESESSION => 1, CURLOPT_AUTOREFERER => 1, CURLOPT_CONNECTTIMEOUT => 120,
CURLOPT_USERAGENT => "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.5) Gecko/2008120121 Firefox/3.0.5",
CURLOPT_AUTOREFERER => 120, CURLOPT_TIMEOUT => 120, CURLOPT_MAXREDIRS => 10, CURLOPT_COOKIEFILE => 'cookiefile', CURLOPT_COOKIEJAR => 'cookiefile', ),
(!empty($configs)
); /** * Hold runtime configuration. * * * @var array * @access protected */ protected $_configs = array(); /** * Class Constructor * * @param array $configs * @access public * @return unknown */ function __construct($configs = array()){ i
f) { $this->setOptions($configs); } else { $this->setOptions($this->__defaultConfigs); } } /** * Configure the class. * * @param array $configs, configuration data. * @return unknown * @access public */ public function &setOptions($configs){
s->_curlInstance = curl_init(); $this->setCurlOptions($this->_co
$this->_configs = array_merge($this->__defaultConfigs, $configs); return $this; } /** * Get Curl Instance. * * @return object curl instance * @access protected */ protected function &_getCurlInstance() { if ($this->_curlInstance == null) { $th
infigs['curlOptions']); } return $this->_curlInstance; } /** * Set Curl Options from array * * @param array $options * @return object | this * @access public */ public function &setCurlOptions($options = array()) { $c = $this->_getCurlInstance(); if (function_exists('curl_setopt_array')) {
rm data * @return string | curl r
curl_setopt_array($c, $options); } else { foreach ($options as $key => $value) { curl_setopt($c, $key, $value); } } return $this; } /** * Execute curl library function. * * @param string $url * @param string $method, http method, 'get' or 'post' * @param string|array $postFields, f
oesponse object * @access public */ public function curlExecute($url, $method = 'get', $postFields = null){ $c = $this->_getCurlInstance(); if ($method === 'get') { $this->setCurlOptions(array(CURLOPT_URL => $url, CURLOPT_POST => false,
CURLOPT_POSTFIELDS => $postFields));
CURLOPT_HTTPGET => 1)); } elseif ($method === 'post') { $this->setCurlOptions(array(CURLOPT_URL => $url, CURLOPT_POST => true, CURLOPT_HTTPGET => 0,
} else { $this->setCurlOptions(array(CURLOPT_URL => $url)); } return curl_exec($c); } /** * Encode url with urlencode function for unencoded character. * * @param string $url urls to be encoded. * @param string $callback function name as callback function, 'urlencode' or 'raw_urlencode' * @return string encoded url.
, $query); $qu
* @access public */ public function encodeUrl($url, $callback = 'urlencode') { if ($pathOfset = strpos($url, '/', (strpos($url, '://') + 3))) { extract(parse_url($url)); $path = implode('/', array_map($callback, explode('/', $path))); $url = substr($url, 0, $pathOfset) . $path; if (!empty($query)) { parse_str($quer
yery = http_build_query(array_map($callback, $query)); $query = preg_replace('@(\=($|(&)))@is', '\3', $query); // remove tailing = sign from empty variable. $url = $url . "?" . $query; } } return $url; } /** * Get Self Instance. * * @param string $name, name of the instance, default value is 'default'
urn self::$__instances[$name]; } /** * Get url contents us
* @param array $configs, configuration array for the instance * @return object, self instance * @access public * @static */ static public function &getInstance($name = 'default', $configs = array()){ if (is_null(self::$__instances[$name])) { self::$__instances[$name] = new self($configs); } re
ting GET MEthod. * * @param string $url * @param string|array $getData, get data in serialized string or array format. * @return string * @access public */ public function get($url, $getData = null){ if (!is_null($getData)) { if (is_array($getData)) { $getData = http_build_query($getData); } if (strpos($url, '?') === false) { $url .= '?'; }
string or array format.
$url .= $getData; } if ($this->_configs['encodeUrl']) { $url = $this->encodeUrl($url); } if ($this->_configs['client'] === 'php') { return file_get_contents($url); } return $this->curlExecute($url); } /** * Get URL contents using POST method. * * @param string $url * @param string|array $postData, form data in serialized
* @return string * @access public */ public function post($url, $postData = null) { if (is_array($postData)) { $postData = http_build_query($postData); } if ($this->_configs['encodeUrl']) { $url = $this->encodeUrl($url); } return $this->curlExecute($url, 'post', $postData); }

}


Usage Example:
File: example.php


<?php
/**
TTP Client Class Example Script. *
*
H * Example of RayHttp Class Object. *
pyright 2006-200
* PHP Version 5 * * * @copyright C
o8, Md. Rayhan Chowdhury * @package raynux
version 1.0 * @version $Revis
* @subpackage raynux.lab.http * @since
ion: 113 $ * @modifiedby $LastChangedBy: rayhan $
, 15 Jun 2008) $ * @author $Author: rayhan $ * @url $HeadURL: ht
* @lastModified $Date: 2008-06-15 10:30:19 +0600 (Su
ntp://localhost/svn/raynux/trunk/labs/example.php $ * @website www.raynux.com * @license GPL */ /**
ing default configuratio
* Load the http client. */ require_once("rayhttp.php"); /** * METHOD GET. */ /** * Example 1 * * u
sn * default method is curl. * use as a singleton object. */ $content = RayHttp::getInstance()->get("http://google.com");
)->get("http://google.com/search?q=rayhttp"); /** * Example 2 * * using default configur
$content = RayHttp::getInstance()->get("http://google.com/search", array('q' => 'rayhttp')); $content = RayHttp::getInstance
(ation but using php native file_get_contetns method. * use as a singleton object. * static method. */ $content = RayHttp::getInstance()->setOptions(array('client' => 'php'))->get("http://google.com");
et("http://google.com/search?q=rayhttp"); /** * Example 3 * * Take Instance Of the object */ $http = new RayHttp(); $content
$content = RayHttp::getInstance()->setOptions(array('client' => 'php'))->get("http://google.com/search", array('q' => 'rayhttp')); $content = RayHttp::getInstance()->setOptions(array('client' => 'php'))->
g= $http->get("http://google.com"); $content = $http->get("http://google.com/search", array('q' => 'rayhttp')); $content = $http->get("http://google.com/search?q=rayhttp"); /** * METHOD POST. */ /** * Example 4 * * using default configuration */
figs); $http = RayHttp::getInstance(); // get default instance $http2 = RayHttp::getInstance('default2'); // get default2 ins
$content = RayHttp::getInstance()->post("http://example.com/", array('name' => 'rayhttp', 'location' => 'dhaka, bangladesh')); /** * Multiple Instance & Configuration. */ RayHttp::getInstance('default', $configs); RayHttp::getInstance('default2', $co
ntance $http3 = RayHttp::getInstance('default3', $configs); // get default 3 instance $http3->setOptions($configs); // reconfigure default3 instance; /** * Specify Proxy */

RayHttp::getInstance('c')->setCurlOptions(array(CURLOPT_PROXY => '172.19.79.1:3128'))->get("http://www.google.com");

0 comments: