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.

Documentation:

Validation:

$email = 'test@example.com';

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

$ip = '127.0.0.1';

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.';
}

Sanitization:

$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: $c\n';
echo 'After: $sanitized_c\n';
}

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

Lance Cameron Kidwell

31 August 2009

Posted in Coding

In lieu of comments, please talk about this post with smart people at Hacker News Hacker News or, if you're the twittering sort, click this handsome button:

Prove Me Wrong: