Home arrow PHP arrow Page 4 - Sanitizing User Input for an MVC-based Framework in PHP 5

Listing the framework's full source code - PHP

In this fourth part of the series, I show you how to provide this sample MVC-driven framework with the ability to sanitize user input by way of a basic input class.

TABLE OF CONTENTS:
  1. Sanitizing User Input for an MVC-based Framework in PHP 5
  2. The framework's current source files
  3. Building a basic input class
  4. Listing the framework's full source code
By: Alejandro Gervasio
Rating: starstarstarstarstar / 2
June 14, 2010

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

Now that I've added another important component to the framework, it's time to list its source files, so you can have them all available in one place for editing purposes. Here they are:

(.htaccess file)

# Turn on URL rewriting engine

RewriteEngine On

# Disable rewriting for existing files or directories

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

# redirect all other requests to index.php

RewriteRule ^.*$ index.php [PT,L]

(index.php)

<?php

// framework's front controller

// specify parameters for autoloading classes

spl_autoload_register(NULL, FALSE);

spl_autoload_extensions('.php');

spl_autoload_register(array('Autoloader', 'load'));

// define custom ClassNotFoundException exception class

class ClassNotFoundException extends Exception{}

// define Autoloader class

class Autoloader

{

                // attempt to autoload a specified class

                public static function load($class)

                {

                                if (class_exists($class, FALSE))

                                {

                                                return;

                                }

                                $file = $class . '.php';

                                if (!file_exists($file))

                                {

                                                eval('class ' . $class . '{}');

                                                throw new Exception('File ' . $file . ' not found.');

                                }

                                require_once($file);

                                unset($file);

                                if (!class_exists($class, FALSE))

                                {

                                                eval('class ' . $class . '{}');

                                                throw new ClassNotFoundException('Class ' . $class . ' not found.');

                                }

                }

}

// handle request and dispatch it to the appropriate controller

try{

                Dispatcher::dispatch();

}

catch (ClassNotFoundException $e){

                echo $e->getMessage();

                exit();

}

catch (Exception $e){

                echo $e->getMessage();

                exit();

}// End front controller

(Dispatcher.php)

<?php

<?php

class Dispatcher

{

    // dispatch request to the appropriate controller/method

    public static function dispatch()

    {

                $url = explode('/', trim($_SERVER['REQUEST_URI'], '/'));

                array_shift($url);

        // get controller name

        $controller = !empty($url[0]) ? $url[0] . 'Controller' : 'DefaultController';

        // get method name of controller

        $method = !empty($url[1]) ? $url[1] : 'index';

        // get argument passed in to the method

        $arg = !empty($url[2]) ? $url[2] : NULL;

        // create controller instance and call the specified method

                                $cont = new $controller;

        $cont->$method($arg);

    }

}// End Dispatcher class

(MySQL.php)

<?php

class MySQL

{

                private $result = NULL;

                private $link = NULL;

                private static $instance = NULL;

                // return Singleton instance of MySQL class

                public static function getInstance(array $config = array())

                {

                                if (self::$instance === NULL)

                                {

                                                self::$instance = new self($config);

                                }

                                return self::$instance;

                }

               

                // constructor

                public function __construct(array $config = array())

                {

        // grab connection parameters

                                list($host, $user, $password, $database) = $config;

                                if ((!$this->link = mysqli_connect($host, $user, $password, $database)))

                                {

                                                throw new Exception('Error connecting to MySQL : ' . mysqli_connect_error());

                                }

                }

    // perform query

    public function query($query)

    {

        if (is_string($query) and !empty($query))

        {

            if ((!$this->result = mysqli_query($this->link, $query)))

            {

                throw new Exception('Error performing query ' . $query . ' Message : ' . mysqli_error($this->link));

            }

        }

    }

   

                // fetch row from result set

                public function fetch()

                {

        if ((!$row = mysqli_fetch_object($this->result)))

        {

            mysqli_free_result($this->result);

            return FALSE;

        }

        return $row;

                }

    // get insertion ID

    public function getInsertID()

    {

        if ($this->result !== NULL)

        {

            return mysqli_insert_id($this->link);

        }

        return FALSE;

    }

   

    // count rows in result set

    public function countRows()

    {

        if ($this->result !== NULL)

        {

           return mysqli_num_rows($this->result);

        }

        return 0;

    }

   

                // close the database connection

                function __destruct()

                {

                                is_resource($this->link) and mysqli_close($this->link);

                }

}// End MySQL class

(Input.php)

<?php

class Input

{

                private static $instance = NULL;

               

                // get Singleton instance of Input class

                public static function getInstance()

                {

                                if (self::$instance === NULL)

                                {

                                                self::$instance = new self;

                                }

                                return self::$instance;

                }

               

                // get $_GET variable

                public static function get($var = NULL)

                {

                                if (!isset($_GET[$var]))

                                {

                                                return $var;

                                }

                                return mysql_escape_string(trim($_GET[$var]));

                }

               

                // get $_POST variable

                public static function post($var = NULL)

                {

                                if (!isset($_POST[$var]))

                                {

                                                return $var;

                                }

                                return mysql_escape_string(trim($_POST[$var]));

                }

}// End Input class

Now that you have at your disposal the partial source files that comprise the framework, I guess that you be happy to edit them and introduce your own tweaks. So go for it. You'll have a great time!  

Final thoughts

In this fourth installment of the series, I showed you how to provide this sample MVC-driven framework with the ability to sanitize user input by way of a basic input class.

As you may have guessed, there's plenty of room to enhance the existing capabilities of this input class, such as by adding to it some extra methods that more efficiently prevent XSS attacks and SQL injections. But for the moment, this will be left as optional homework for you.

In the upcoming part, I'll continue extending the functionality of the framework, this time by coding an HTML form helper class. So, here's my advice for you: don't miss the next article!



 
 
>>> More PHP Articles          >>> More By Alejandro Gervasio
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: