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:
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".firstname.lastname@example.org or "abcdefghixyz"@example.com are allowed. abc"defghi"email@example.com is not; neither is abc\"def\"firstname.lastname@example.org). 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"@example.com'; $email = filter_var($email, FILTER_SANITIZE_EMAIL);
Then you can validate the email using your validation.