Thursday, January 10th, 2008

PHP HTTPRequest Class

Note: This is is a quick example of a very basic HTTP Request Class in PHP. This would be a nice, practical introduction to classes for someone who has been looking for a place to start.

Problem: By default, request data in PHP is handled by using Super Globals ($_POST, $_GET, $_COOKIES). Globals are bad for several reasons (outside the scope of this example google here). In an effort to remedy this, we need a way to encapsulate the request data into an object. By doing this, we are centralising access to request data through the one channel - the HTTP Request object.

Class Name:HTTPRequest

Responsibilities:

  • Store “request data” in GPC order.
  • Store additional “request data” outside of the super globals referenced by a key.
  • Read stored “request data” by referencing a key.
  • Internally clean request data by handling magic_quotes_gpc and then adding slashes.
  • Allow access to data stored in GET, POST and COOKIE super globals.

Collaborators: Any - the request object is used by any other class or function that requires access to the request data.


Class Code:

# Filename: httprequest.php

<?php
/**
 * HTTPRequest Class
 * @author R. Villar David <my@email.com>
 *
 * Encapsulate request data into the one object providing a
 * single channel for request data access and manipulation.
 *
 */

class HTTPRequest
{
    /**
     * Holds collective request data
     *
     * @var array
     */

    protected $_data = array();

    /**
     * Holds data from the $_POST super global
     *
     * @var array
     */

    protected $_post = array();

    /**
     * Holds data from the $_GET super global
     *
     * @var array
     */

    protected $_get = array();

    /**
     * Holds data from the $_COOKIE super global
     *
     * @var array
     */

    protected $_cookie = array();

    /**
     * Constructor
     * Stores "request data" in GPC order.
     */

    public function __construct()
    {
        $this->_data = array_merge($this->_data, $_REQUEST);
        $this->_get = array_merge($this->_get, $_GET);
        $this->_post = array_merge($this->_post, $_POST);
        $this->_cookie = array_merge($this->_cookie, $_COOKIE);
        $this->_clean();
    }

    /**
     * Store "request data" in GPC order.
     *
     * @param string $key
     * @param mixed $value
     */

    public function set($key, $value)
    {
        $this->_data[$key] = $value;
    }

    /**
     * Read stored "request data" by referencing a key.
     *
     * @param string $key
     * @return mixed
     */

    public function get($key)
    {
        return isset($this->_data[$key]) ? $this->_data[$key] : null;
    }

    /**
     * Allow access to data stored in GET, POST and COOKIE super globals.
     *
     * @param string $var
     * @param string $key
     * @return mixed
     */

    public function getRawData($var, $key)
    {
        switch(strtolower($var)) {
            case ‘get’:
            $array = $this->_get;
            break;

            case ‘post’:
            $array = $this->_post;
            break;

            case ‘cookie’:
            $array = $this->_cookie;
            break;

            default:
            $array = array();
            break;
        }

        if(isset($array[$key])) {
            return $array[$key];
        }
        return null;
    }

    /**
     * Internally clean request data by handling magic_quotes_gpc and then adding slashes.
     *
     */

    protected function _clean()
    {
        if(get_magic_quotes_gpc()) {
            $this->_data = $this->_stripSlashes($this->_data);
            $this->_post = $this->_stripSlashes($this->_post);
            $this->_get = $this->_stripSlashes($this->_get);
        }
    }

    /**
     * Strip slashes code from php.net website.
     *
     * @param mixed $value
     * @return array
     */

    protected function _stripSlashes($value)
    {
        if(is_array($value)) {
            return array_map(array($this,‘_stripSlashes’), $value);
        } else {
            return stripslashes($value);
        }
    }
}

Example Usage

# Example Usage
require ‘httprequest.php’;

$request = new HTTPRequest();
$request->set(‘testvar’,‘123′);
$message = ‘Username and Password submitted’;
echo ‘<h1>Simulated Form: </h1>’;
echo ‘<form action="?submit_message=’.urlencode($message).‘" method="post" style="width: 40em; font-size: 0.9em;">’;
echo ‘<fieldset>’;
echo ‘<legend style="font-weight: bold">Demo login</legend>’;
echo ‘<label for="username" style="display: block; float: left; width: 110px;">username:</label><input type="text" id="username" name="username" value="’.$request->get(‘username’).‘" /><br />’;
echo ‘<label for="password" style="display: block; float: left; width: 110px;">password:</label><input type="password"  id="password" name="password" value="’.$request->get(‘password’).‘" /><br />’;
echo ‘<input value="submit" type="submit"/><br />’;
echo ‘<input type="hidden" value="submitted" name="submitted"/>’;
echo ‘</fieldset>’;

if($request->get(’submitted’)) {
    echo ‘<div style="border: 1px solid #000; padding: 5px; margin-top: 20px;">’;
    echo ‘<span style="font-weight: bold;">Form submitted with the following values:</span>’;
    echo ‘<ul style="color: #f00;">’;
    echo ‘<li>submit Message (query string):’.$request->get(’submit_message’).‘</li>’;
    echo ‘<li>testvar (manually set variable):’.$request->get(‘testvar’).‘</li>’;
    echo ‘<li>username (text field):’.$request->get(‘username’).‘</li>’;
    echo ‘<li>password (text field):’.$request->get(‘password’).‘</li>’;
    echo ‘</ul>’;
    echo ‘</div>’;
}

echo ‘</form>’;

Download
HTTPRequest Class

As demonstrated in the code provided in the Example Usage section, the HTTPRequest class provides a centralised solution for handling request data.

This is a just base which you could build on top, or around of if you need more complex request data handling.

All in all a very simple class. Super globals are copied and “cleaned” in the constructor, getters and a setter to give you a channel where you can store your custom request data.

One of the things I take for granted with this class is the fact that I don’t need to manaully check for existing variables (eg if(isset($_POST[’var’])) {) as this operation is abstracted in the get() method. If you try to access a variable that is not there, you will simply get a null value - notices need not be suppressed anymore.

Another feature that I did not set up an example for is the getRaw() method which allows you to access a variable from a specific super global, instead of relying on the data acquired from the $_REQUEST super global. While I did have a use for this, it was a special case scenario, but I thought I’d add it in to exemplify how you could add your own methods.

As you advance, you may find that you will need to add further support - such as providing the remote IP address, reading the URI string etc.

» Filed under Classes & Examples by rvdavid at 11:49.

back to top

2 comments
to PHP HTTPRequest Class

  1. James

    on Thursday, July 10th, 2008 at 2:35 am:

    Thanks for wasteing my time - I got this:

    Fatal error: Call to undefined method HttpRequest::set() in ….

  2. on Thursday, July 10th, 2008 at 10:40 am:

    Really? I don’t believe you. ;)
    I tested this class before posting (and again just then)

    Try this:
    - Click on the TXT link under the heading “download”
    - Copied the contents
    - Paste into your a php file and run it.

Subscribe to comments or TrackBack to PHP HTTPRequest Class

Leave a comment





Credits:

© rvdavid: A Web Developer’s Blog | Powered by WP 2.3.1

Tree theme modified based on headsetoptions