Validate and sanitize email address in PHP
Wednesday, December 21, 2011 EST
by: Eric Potvin
Tags:php
PHP added a very useful function to validate variables like email, url etc... 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 wont 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".xyz@example.com or "abcdefghixyz"@example.com are allowed. abc"defghi"xyz@example.com is not; neither is abc\"def\"ghi@example.com). 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);
Will output:
string(21) "user.name@example.com"
Then you can validate the email using your validation.
Link to this Article
To link directly to this article from your web site, use one of the following snippets below.
Validate and sanitize email address in PHP | Book Of Zeus<a href="http://www.bookofzeus.com/articles/validate-and-sanitize-email-address-in-php/" title="Validate and sanitize email address in PHP">Validate and sanitize email address in PHP | Book Of Zeus</a>
Short URL:
Validate and sanitize email address in PHP | Book Of Zeus<a href="http://s.bookofzeus.com/elR8z" title="Validate and sanitize email address in PHP Short URL">Validate and sanitize email address in PHP | Book Of Zeus</a>