Validate and sanitize email address in PHP

Posted on Tuesday December 20, 2011 / by Eric Potvin

PHP added a very useful function to validate variables like email or url. Since PHP 5.2.0, the filter_var function allow the developer to validate email address using this simple code:

filter_var($email, FILTER_SANITIZE_EMAIL);

Now, this will not validate everything. Regarding wikipedia, an email address with non-alpha numeric characters, like double quotes, are considered valid.

A quoted string may exist as a dot separated entity within the local-part or it may exist when the outermost quotes are the outermost chars of the local-part (e.g. abc."defghi" or "abcdefghixyz" are allowed. abc"defghi" is not; neither is abc\"def\" Quoted strings and characters however, are not commonly used. RFC 5321 also warns that "a host that expects to receive mail SHOULD avoid defining mailboxes where the Local-part requires (or uses) the Quoted-string form" (sic).

Here's how to fix this:

$email = 'user."name"';
$email = filter_var($email, FILTER_SANITIZE_EMAIL);

Will output:

string(21) ""

Then you can validate the email using your validation.