Regan Johnson - Web Design, Marketing, SEO
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, including whitespace that isn't trailing or leading
public function whitespace($str){
retrun preg_replace('/\s\s+/',' ', $str);
}
// Removes characters not valid in an e-mail address
public function email($email){
return strtolower(preg_replace('/[^a-z0-9+_.@-]/i','',$email));
}
// Removes tags, whitespace
public 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;
}
}
?>
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'] = "23.554";
// $_POST['email'] = 'random spaces %%+symbols@ domain.com';
$name = $filter->text($_POST['name']);
$age = intval($_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 23 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.
9 people have left comments
SEO Ranter said:
Can someone please forward this over to Wordpress?
http://search.securityfocus.com/swsearch?query=wordpress&metaname=alldoc
Stilegrafica Design Blog » Blog Archive » 5 script PHP che forse non conoscevi said:
[…] Filtrare l’input utente con PHP […]
Missfitbit said:
Ok, just learning (stop groaning), so a little help would be awesome.
Building a site whose main function will be compiling blurbs about events (etc) that will also be e-mailed to subscribers. So, obviously, I need to collect e-mail addresses, send html emails to my users, and allow users to remove their address. Yep, there are a TON of third parties that will do this for you, but i want to own and have total control over my data, plus it’s just fun to learn. I just don’t want to have my subscribers be overrun with spam et al. because I didn’t know enough. So…
I’m going to use everything on this page, but you mentioned you’d send more info on e-mail validation, verification, etc, so could you?
Any other tips or resources? (Besides “hire someone”)
Thanks a MILLION!
Robert Augustin said:
Hi Regan,
I just came across your site and I already love it. Thanks for this post in particular - I’m no pro at PHP just yet and this kind of info is great!
Question - why strip user input from whitespaces? As an example, let’s say it’s a contact form using a textarea for a message, the contact.php (form) posts to formmailer.php (script), which checks for sanity, empty fields and email validity and on error, returns to contact.php with a conditional DIV displaying the error message (so far so good).
Why eliminate all whitespaces? User’s message would be unreadable in this case.
Or am I getting it wrong ![]()
Regan Johnson said:
Robert Augustin said: Hi Regan,
I just came across your site and I already love it. Thanks for this post in particular - I’m …
Hey there Robert,
Thanks for the comment. The function I am using in this example will eliminate whitespace (which is anything more that 1 space). This is particularly useful when people try to enter something with an exorbitant amount of spaces in between words, and will clean up the input passed to your application.
Hope this helps!
dreamMonkey said:
Hi Regan,
first of : great site ! Just what I was looking for !
I am currently trying to rebuild someone’s website that we believe fell victim to malicious practices you are trying to protect us from. I really want to make it as strong as possible that ’s why I was wondering what more methods one could us in the class to make it as solid as a rock?PS: I’m very interested in the MySQL protection update as well !
regards,
dreamMonkey
Michael said:
Nice class, but wondered about one thing. If/when the filter finds input data that breaks the filter rules, how would you go about displaying a warning to the user that their data has issues and won’t be accepted? This would be great if it could appear on the actual form page before getting to the input process on another page.
- Copyright 2010 Web Design, Marketing, SEO & Clean CSS | SOAPTRAY. All Rights Reserved.
- Back To Top
- Home
- FFF






Leave a Comment-