Handling user input with PHP 5.2
One of the new wonders in PHP 5.2 is the filter extension. This extension has just seven function, but still provides an extremely powerful way of handling user input.
- filter_has_var - Checks if variable of specified type exists
- filter_id - Returns the filter ID belonging to a named filter
- filter_input_array - Gets multiple variables from outside PHP and optionally filters them
- filter_input - Gets variable from outside PHP and optionally filters it
- filter_list - Returns a list of all supported filters
- filter_var_array - Gets multiple variables and optionally filters them
- filter_var - Filters a variable with a specified filter
Why do I have to do all this?
Because your users are evil, and want to destroy your data.
In other words, in order to protect you from among others, the following attacks.
- Cross Site Scripting
- SQL injection
- HTTP Header Injection
- HTTP response splitting
If you want more information about the different attack types, check Wikipedia.
Ok, I get the point. Show me some code.
Sure, let's start with a simple example.
You have probably seen this many times before:
$sql = “SELECT * FROM posts WHERE postID = ‘”.$_GET[‘id’].“‘”;
Let's make sure that our ID does not contain any malicious code, that will hurt our database. In fact, let's make sure it's a integer.
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT); $sql = “SELECT * FROM posts WHERE postID = ‘”.$id.“‘”;
The code above will try to sanitize the supplied ID into a number.
We can also make sure a ID is supplied.
if(filter_has_var(FILTER_GET, 'id')) {
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
$sql = “SELECT * FROM posts WHERE postID = ‘”.$id.“‘”;
} else {
echo "Please supply a ID.";
A third example could be something like this.
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if($id === false) {
$sql = “SELECT * FROM posts WHERE postID = ‘”.$id.“‘”;
} else {
echo "Please supply a number as ID.";
If you are collecting data from many fields in a form, and want to validate/filter them all in one big chunk, you can use filter_input_array().
$args = array( 'name' => FILTER_SANITIZE_STRING, 'email' => FILTER_VALIDATE_EMAIL, 'website' => FILTER_VALIDATE_URL, ); $res = filter_input_array(INPUT_POST, $args);
The $res array will look something like this:
array( ['name'] => 'Foo Bar', ['email'] => 'foo@example.com', ['website'] => 'http://example.com', )
If a value that does not validate according to the specified filter is entered, the field will have a bool false in the $res array.
This was a really short introduction to PHP filter. You can find more information about the various functions and filters in the PHP manual.
Post new comment