Validating email addresses in PHP made simple

An important aspect of processing user input on a website should be filtering it. Primarely for security reasons, but also to have valid data. Since PHP 5.2 it is very easy to validate (and sanitize) user input using the filter functions. But a lot of PHP developers seem not to be aware of them and create their own filters using regular expressions. Which is very easy to get wrong. So I highly recommend the built-in PHP filters.

Here is a simple example for validating email addresses:


if( !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ) {
    echo 'Invalid email address';
}

Because who needs invalid data?