Written by 3:39 pm Coding

PHP Validation and Sanitization with filters

One of the most common problems in web development in validating and sanitizing user inputted data. Often, we’re tempted to reinvent the wheel when validating emails, ranges, booleans, etc.

Fortunately, php has a lot of these tasks already written. You can use the built in filters to validate and sanitize in a manner that’s already been tested and optimized by the core developers.



$email = 'test@example.com';

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo 'This (email) email address is considered valid.';

$ip = '';

if (filter_var($ip, FILTER_VALIDATE_IP)) {
echo 'This (ip) IP address is considered valid.';

$int_example = '4';
$options = array(
'options' => array(
'min_range' => 0,
'max_range' => 3,

$options['options']['default'] = 1;
if ($int_example = filter_var($int_c, FILTER_VALIDATE_INT, $options)) {
echo 'This (int_example) integer is considered valid (between 0 and 3) and is $int_example.';


$c = '(bogus@example.org)';

$sanitized_c = filter_var($c, FILTER_SANITIZE_EMAIL);
if (filter_var($sanitized_c, FILTER_VALIDATE_EMAIL))
echo 'This (c) sanitized email address is considered valid.n';
echo 'Before: $cn';
echo 'After: $sanitized_cn';

$search_html = filter_input(INPUT_GET, 'query', FILTER_SANITIZE_SPECIAL_CHARS);