Useful Snippets

Welcome!


This blog is used to collect useful snippets related to Linux, PHP, MySQL and more. Feel free to post comments with improvements or questions!

RSS Latest posts from my personal blog


Most viewed posts


Subscribe to RSS feed


Introduction to PHP data validation with validation filters

Stanislav KhromovStanislav Khromov

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.

PHP

Web Developer at Aftonbladet (Schibsted Media Group)
Any opinions on this blog are my own and do not reflect the views of my employer.
LinkedIn
Twitter
WordPress.org Profile
Visit my other blog

Comments 0
There are currently no comments.