Simple PHP Input Validation - filter_var()

A large chunk of your project’s time is going to be devoted to input validation. Sanitising the data that was typed into the form is essential to maintaining your application’s security. Mattias Geniar, over on his blog, talks about using PHP’s filter_var function which is a simple pecl install filter away. He explains how we can change something from this:

<?php

$filter = "^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,4})$";
if (!eregi($filter, $user_email)) {
	echo "Invalid e-mail address.";
}

..to this:

<?php

if (!filter_var($user_email, FILTER_VALIDATE_EMAIL)) {
	echo "Invalid e-mail";
}

..along with a host of other filters and sanitiser which, believe it or not, are not documented on the man page.

Check his great article out at http://mattiasgeniar.be/2009/02/07/input-validation-using-filter_var-over-regular-expressions/.