Rayhan’s blog (raynux.com)

Rayhan’s Personal Web Blog Site

Entries Comments


Http Client Class for PHP development

13 June, 2009 (13:01) | PHP, programming, Reference

Tags: , , , ,


RayHttp, A Simple Http Client Class for PHP Development.

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.
 *
 * A basic HTTP Client desinged for php developer.
 * - CURL
 * - Native php method
 *
 *	PHP Version 5
 *
 *
 *	@copyright		Copyright 2006-2008, Md. Rayhan Chowdhury
 *	@package		raynux
 *	@subpackage		raynux.lab.http
 * 	@since			version 1.0
 *	@version		$Revision: 113 $
 * 	@modifiedby		$LastChangedBy: rayhan $
 *	@lastModified	$Date: 2008-06-15 10:30:19 +0600 (Sun, 15 Jun 2008) $
 *	@author			$Author: rayhan $
 *	@url			$HeadURL: http://localhost/svn/raynux/trunk/labs/rayhttp.php $
 *	@website		www.raynux.com
 *  @license 		GPL
 */

/**
 * HTTP Client Class.
 *
 * A basic HTTP Client desinged for php developer.
 * - CURL
 * - Native php method
 *
 *
 * @todo add utf-8 conversion.
 * @todo add plugins functionality
 *
 *
 * @package raynux
 * @subpackage raynux.lab.http
 * @version 1.0
 * @since version 1.0
 * @author Md. Rayhan Chowdhury
 */
class RayHttp{

	/**
	 * Hold runtime instance of self
	 *
	 * @var array of self instances
	 * @access private
	 * @static
	 */
	static private $__instances;

	/**
	 * Curl Instance
	 *
	 * @var object Curl instance
	 * @access protected
	 */
	protected 	$_curlInstance = null;

	/**
	 * Default configuration for the crawler.
	 *
	 * @var array
	 * @access private
	 */
	private 	$__defaultConfigs = array(
                    'client' => 'curl',
                    'encodeUrl' => true,
                    'curlOptions' => array(
                        CURLOPT_SSL_VERIFYPEER => 0,
                        CURLOPT_RETURNTRANSFER => 1,
                        CURLOPT_FOLLOWLOCATION => 1,
                        CURLOPT_ENCODING => "",
                        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_COOKIESESSION => 1,
                        CURLOPT_AUTOREFERER => 1,
                        CURLOPT_CONNECTTIMEOUT => 120,
                        CURLOPT_AUTOREFERER => 120,
                        CURLOPT_TIMEOUT => 120,
                        CURLOPT_MAXREDIRS => 10,
                        CURLOPT_COOKIEFILE => 'cookiefile',
                        CURLOPT_COOKIEJAR => 'cookiefile',
                    ),
                );

	/**
	 * Hold runtime configuration.
	 *
	 *
	 * @var array
	 * @access protected
	 */
	protected 	$_configs = array();

	/**
	 * Class Constructor
	 *
	 * @param array $configs
	 * @access public
	 * @return unknown
	 */
	function __construct($configs = array()){
		if (!empty($configs)) {
			$this->setOptions($configs);
		} else {
			$this->setOptions($this->__defaultConfigs);
		}
	}

	/**
	 * Configure the class.
	 *
	 * @param array $configs, configuration data.
	 * @return unknown
	 * @access public
	 */
	public function &setOptions($configs){
		$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) {
			$this->_curlInstance = curl_init();
			$this->setCurlOptions($this->_configs['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')) {
			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, form data
	 * @return string | curl response 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_HTTPGET => 1));

		} elseif ($method === 'post') {
			$this->setCurlOptions(array(CURLOPT_URL => $url,
                                        CURLOPT_POST => true,
                                        CURLOPT_HTTPGET => 0,
                                        CURLOPT_POSTFIELDS => $postFields));

		} 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.
	 * @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($query, $query);
				$query = 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'
     * @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);
    	}
    	return self::$__instances[$name];
    }

	/**
	 * Get url contents using 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 .= '?';
    		}
    		$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 string or array format.
     * @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
/**
 * HTTP Client Class Example Script.
 *
 * Example of RayHttp Class Object.
 *
 *	PHP Version 5
 *
 *
 *	@copyright		Copyright 2006-2008, Md. Rayhan Chowdhury
 *	@package		raynux
 *	@subpackage		raynux.lab.http
 * 	@since			version 1.0
 *	@version		$Revision: 113 $
 * 	@modifiedby		$LastChangedBy: rayhan $
 *	@lastModified	$Date: 2008-06-15 10:30:19 +0600 (Sun, 15 Jun 2008) $
 *	@author			$Author: rayhan $
 *	@url			$HeadURL: http://localhost/svn/raynux/trunk/labs/example.php $
 *	@website		www.raynux.com
 *  @license 		GPL
 */

/**
 * Load the http client.
 */
require_once("rayhttp.php");

/**
 * METHOD GET.
 */

/**
 * Example 1
 *
 * using default configuration
 * default method is curl.
 * use as a singleton object.
 */
$content = RayHttp::getInstance()->get("http://google.com");
$content = RayHttp::getInstance()->get("http://google.com/search", array('q' => 'rayhttp'));
$content = RayHttp::getInstance()->get("http://google.com/search?q=rayhttp");

/**
 * Example 2
 *
 * using default configuration 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");
$content = RayHttp::getInstance()->setOptions(array('client' => 'php'))->get("http://google.com/search", array('q' => 'rayhttp'));
$content = RayHttp::getInstance()->setOptions(array('client' => 'php'))->get("http://google.com/search?q=rayhttp");

/**
 * Example 3
 *
 * Take Instance Of the object
 */
$http = new RayHttp();
$content = $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
 */
$content = RayHttp::getInstance()->post("http://example.com/", array('name' => 'rayhttp', 'location' => 'dhaka, bangladesh'));

/**
 * Multiple Instance & Configuration.
 */
RayHttp::getInstance('default', $configs);
RayHttp::getInstance('default2', $configs);

$http = RayHttp::getInstance(); // get default instance
$http2 = RayHttp::getInstance('default2'); // get default2 instance

$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");

Rate this class at phpclasses.org: http://www.phpclasses.org/rayhttpclient

«

  »

Comments

Comment from Peter
Time: June 15, 2009, 4:20 am

You can make the REST and HTTP calls using Eclipse Http4e. It is an amazing tool for SOAP, REST or simply replaying HTTP calls.

http://http4e.roussev.org/

Comment from Abdelali
Time: June 15, 2009, 2:31 pm

Hello,
First thank you for this perfect CLASS, i want just know if CURLOPT_USERAGENT must be changed to work with IE or safari…or any other browser?

Comment from Rayhan Chowdhury
Time: June 15, 2009, 11:01 pm

@ Abdelali

the class works at server. so it is browser independent. no need to change user agent value.

Comment from php
Time: July 23, 2009, 6:04 pm

The class working perfectly .no need to changing anything

Comment from Portation
Time: August 29, 2009, 4:38 am

Can also play a big role
http://www.webportationbd.com/

Comment from Pete Michaud
Time: December 14, 2009, 1:33 am

This is a nice class, good work. I’m wondering though, how do I capture cookies? I see CURL options in there related to cookies, but for example, with he Zend Framework I’d have to call “->setCookieJar();” on my Zend http cbject, then it would store them (for example, if I wanted to log in with a post request, then immediately see a page in the password protected area via a different get request).

Right now if I use a RayHttp Object and call ->post() to log in, then follow it with a ->get(), my get just grabs the login page html.

Any ideas?

Comment from Md. Rayhan Chowdhury
Time: December 16, 2009, 12:55 pm

Setting these curl options will help,

CURLOPT_COOKIE
CURLOPT_COOKIEFILE
CURLOPT_COOKIEJAR

Comment from research papers
Time: March 18, 2010, 11:34 pm

thanks for info, I’ll use it, what kind of copyright should I put?

Comment from ClubPenguinCheats
Time: March 22, 2010, 11:43 am

First thank you for this perfect CLASS, i want just know if CURLOPT_USERAGENT must be changed to work with IE or safari…or any other browser?

Write a comment