How-To Validate / Sanitize Data in PHP

Friday, 7th December 2012

In this post, I will tackle a very important (and usually ignored topic) when programming in PHP.

Data validation and sanitization is not only important at the business level, but also very important at the security level since this is where most attacks usually take place especially when dealing with SQL injection and Cross-Site Scripting attacks.

Assuming you have a piece of data that you have read from a form as follows:

$data = $_POST['data'];

Data sanitzation and validation is very co-related in here. Validation allows you to tell whether the data is valid or not without changing the value of the data itself. Sanitization, on the other hand, means removing invalid entries from the data to make it sane (as opposed to insane ;)

For this purpose, PHP has a very helpful method: filter_var

filter_var:The Function

filter_var filters a variable with a specified filter.

Its syntax is as follows:
mixed filter_var(mixed $variable[,int $filter=FILTER_DEFAULT[,mixed $options]])

The function returns the filtered data, or FALSE if the filter fails.

A simple example follows:
var_dump(filter_var('', FILTER_VALIDATE_EMAIL));

The first line requests to validate as a valid email.
Its output will be: string(15) ""

The second line requests to validate as a valid URL with a path (which is not the case here).
Its output is: bool(false)

Possible filters are listed below:

The following sanitization filters are available: