Just because everyone is allowed on the Internet, it doesn’t mean they are qualified to use it correctly or they are just people who make mistakes. Programmers need to correct these things and therefore validation of external input is very important for a secure website. Email addresses are one of the hardest things to validate because you got so many possibilities.
Validating of an email address mostly begins with a good regular expression which represents any possible email address. Searching on Google lead me to Ian Dunn, he made a nice list on possibilities an email address can have and gathered all attempts for a regex and tested it on this list. The most accurate, near perfect, regular expression came from Alexandre De Dommelin, which I used in my script.
I wasn’t fully pleased with the regular expression, so I wanted to validate the domain even more. A function in PHP 4+ allows to check whether MX records on a certain domain, just what I needed. Now the validation is perfect, I hope. The function is described below, it should be reusable in any project using PHP 4 or newer, please include credits. Code released under Creative Commons Attribution-Share Alike 2.0 Belgium License
function check_email($email) {
//Function written by Jeroen Op 't Eynde - XprsYrslf.be
//Creative Commons Attribution-Share Alike 2.0 Belgium License
//Pattern from: http://fightingforalostcause.net/misc/2006/compare-email-regex.php
$pattern = "/^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|asia|cat|jobs|tel|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i";
if (function_exists('checkdnsrr')){
$domain=strstr($email,'@');
if(preg_match($pattern,$email) && checkdnsrr($domain,"MX")) return $email; //Linux: PHP 4.3.0 & Windows: PHP 5.3.0
else return false;
} else {
if(preg_match($pattern,$email)) return $email; //PHP 4 or 5
else return false;
}
}
Please report any bugs/comments here or via the contact form.
Update:
On debugging a project, PHP threw some notices on the split() function. It seems to be a deprecated function. I simply replaced it with the strstr() function. Below is the line I took out.
list($user,$domain) = split('@',$email);

check also the php own filter functions to validate a mail address:
http://nl.php.net/manual/en/filter.filters.validate.php