farfromfearless

Hello, my name is Regan Johnson, and soaptray is my Blog and online portfolio; I am currently the Director of Technology for Datepad.com Read More

Filtering User Input in PHP

Never trust input. I have said this many times before, and am always cognizant of this phrase when I am developing new websites or web applications. Always assume that someone is going to try to exploit your program - be it with malicious intentions or not.

With this article, I want to shed some light on some of the ways to protect the security, quality and integrity of you web applications written in PHP and MySQL. There is always going to be rotten people out there that want to take advantage of a poorly secured or filtered program - think of it like someone breaking into a house that has no locks on the front door.

What is XSS or Cross-site Scripting?

XSS is a method in which malicious users can inject client side scripts into web applications to gain information, bypass user authentication controls and other such things. This is a vulnerability that I see too often because people are trusting user input data - this is something that can be easily avoided using some simple filtering steps.

Filtering incoming data

There are many aspects of filtering - or sanitizing - that you must consider when accepting user generated input (think forms, profiles, contact us). For the purpose of this article, I will be placing the individual filters as methods of a class, that is loaded only when we need to deal with filtering data. This method of doing things is efficient, and uses OOP or Object Oriented Programming techniques (another article on that one later!).

Building the filter class

I have chosen to use a custom filter class, rather then available extensions, simply because I like to tune each class for the project I am working with - this reduces the amount of code that is being loaded and used.

Using a class may be new to some programmers, but let me assure you that it is well worth it in the end for a number of reasons (mainly scalability, code re-use and ease of changes/updates). A class is comprised of many different methods (which act very similar to functions). I will write another article on classes, but for some more information on the basics of classes, you can take a look at the php.net introduction to classes and objects.

First, let’s start by building a basic class as an include that we will load when needed. Let’s name this file [ class-filter.php ]

class-filter.php

<?php

class filter {

}

?>

Now that we have our class defined, let’s add some methods (functions) to it to filter various types of information.

class-filter.php (continued)

<?php

class filter {

	// Removes all whitespace from a string
	function whitespace($str){
		$str = preg_replace('/\s\s+/',' ', $str);
		return $str;
	}

	// Removes characters not valid in an e-mail address
	function email($email){
		$email = preg_replace('/[^a-z0-9+_.@-]/i','',$email);
		$email = strtolower($email);
		return $email;
	}

	// Removes tags, whitespace
	function text($str){
		// Ensure it's a string
		$str = strval($str);
		// We strip all html tags
		$str = strip_tags($str);
		// Remove any whitespace using
		// the define method above
		$str = $this->whitespace($str);
		return $str;
	}

	// Return the input as an integer
	function integer($int){
		$int = intval($int);
		return $int;
	}

}

?>

This list can go on for a while, and get quite specific depending on what type of information you wish to filter. I use a much more complicated version in many of my projects that include e-mail validation, verification and more (I would be happy to share some of these with anyone interested - just drop me a comment).

I encourage you all to add project specific methods (functions) to your filter class.

Now that we have our filter class ready, let’s open up our main project file [ index.php ] and include our class file, then initiate the class into an object that we can use to filter data.

index.php

<?php

// We first include our class
include 'class-filter.php';

// And then we initiate the class (filter) as an object ($filter)
$filter = new filter();

?>

That’s it, we are now ready to start filtering data! Let’s say that we have a form posting to [ index.php ] with several different user values - take a look at the blow example to show you how to filter them.

index.php (continued)

<?php

// We first include our class
include 'class-filter.php';

// And then we initiate the class (filter) as an object ($filter)
$filter = new filter();

// Let's say they are posting the following from a form:
// $_POST['name'] = 'Regan Johnson<? die("Muahaha"); ?>';
// $_POST['age'] = "22.554";
// $_POST['email'] = 'random spaces %%+symbols@ domain.com';

$name = $filter->text($_POST['name']);
$age = $filter->integer($_POST['age']);
$email = $filter->email($_POST['email']);

echo "Hello, my name is $name.“;
echo “I am $age years old.“;
echo “My e-mail address is $email.“;

// Hello, my name is Regan Johnson.
// I am 22 years old.
// My e-mail address is randomspaces+symbols@domain.com.

?>

From the above example, you can see that the data is filtered from potentially malicious scripts (XSS) breaking data to harmless data that is expected by (and works with) your program.

Now that the data is not harmful, the next step is to check for errors. An example of error checking for an e-mail address can be seen in my previous article,
Validate e-mail addresses using PHP and DNS.

Finally, you will want to enter the data into your database, or use it as you would like in your web application. I will be completing an article soon on MySQL security, and simple ways to prevent what is known as a MySQL Injection Attack - I will link it here when it’s finished.

Thanks for reading my article about filtering forms and incoming data in PHP. I would love to hear some methods that you use in your filtering process - please leave a comment below. As always, if you enjoy my articles please subscribe to my RSS Feed.

  • Apr 2008
  • 8

Validate e-mail addresses using PHP

As a PHP programmer, there are a lot of people in this world that piss me off - collectively I...

  • Apr 2008
  • 1

A new blog is born

A quick introduction for this blog, and Regan Johnson, the creative mogul behind Soaptray. I hope to use this blog...

Older Posts-

Flickr Photostrem-

Delicious ChickenSpider businessTree ToadTree ToadKing Edward Beach SunsetKing Edward Beach Sunset