Filtering PHP Input
I wrote a blog for the company I work for not too long ago expressing the need and importance of filtering PHP input. It never really ceases to amaze me the amount of people who trust the raw user input from forms, which we all know can lead to some serious security gaps.
In response to the huge amount of people who don’t validate user input, I decided to write a class that would help people out who are in need of cleaning user input, but aren’t really sure how to approach it.
First we’ll start with a class, which for this example I’ll call class.filter.php
<?
class filter {
function whitespace($str){
$str = preg_replace('/\s\s+/',' ', $str);
return $str;
}
function email($str){
$str = preg_replace('/[^a-z0-9+_.@-]/i','',$str);
$str = strtolower($str);
return $str;
}
function text($str){
$str = strval($str);
$str = strip_tags($str);
$str = $this->whitespace($str);
return $str;
}
function integer($int){
$int = intval($int);
return $int;
}
}
?>
Now that’s just a few basic commands, these filtering classes can get pretty complex and soon I plan on releasing a more complex version of this filtering class, but for now this will do.
Next we’ll move on how to use this class. Let’s assume we have a contact form with three fields: name, email, and age.
<?
include_once ('class.filter.php');
$filter = new filter();
$name = $filter->text($_POST['name']);
$age = $filter->integer($_POST['age']);
$email = $filter->email($_POST['email']);
echo 'Hello, '.$name.' (Age: '.$age.')<br />'."\n";
echo 'Thanks for registering your email address <em>'.$email.'</em>'."\n";
?>
Now by doing this, you’re preventing dangerous XSS (Cross Site Scripting), and making the data input pretty tame. Now the next step after cleaning up the input is validating it to ensure that it’s the data you are looking for, but we can save that for another day.