Category Archives: Security

Introduction to PHP data validation with validation filters

PHP comes with built in validation filters, so you can validate emails, numbers and urls and more without writing any code.

Here is a list of all available validation filters.

To use it, we pick a filter and pass it to the filter_var() function together with the data we want to validate.

Example 1 – Email validation

$string = 'bob@bobcorp.net';
var_dump(filter_var($string, FILTER_VALIDATE_EMAIL));

Output

string(15) "bob@bobcorp.net"

When validation succeeds, we get the string back. But what if the validation is unsuccessful?

$string = 'definitely-not^an_email';
var_dump(filter_var($string, FILTER_VALIDATE_EMAIL));

Output

bool(false)

Great, we get false back! Now to put it together:

$string = 'bob@bobcorp.net';

if(filter_var($string, FILTER_VALIDATE_EMAIL)!==false)
    echo "Totally validated!";

Output

Totally validated!

Example 2 – Validating an integer with a minimum and maximum values

Some validators have options. The FILTER_VALIDATE_INT validator has two options, min_range and max_range. You can specify these to limit which integers will be valid. (In our case, only 10 – 20 is considered valid).

$number = 15;
var_dump(filter_var($number, FILTER_VALIDATE_INT, array('options' => array('min_range' => 10, 'max_range' => 20))));

Output

int(15)

Great! The number got validated and we got it back. If validation would have failed we would have gotten bool(false), like in Example 1.

That covers basic validation with PHP. Before saving any user-entered data, you should use sanitize filters to sanitize the data. Sanitization filters work similarly to validation filters – the difference is that sanitization filters alters the data you send to filter_var to make it conform to the filter criteria.