PHP Validate Email Address
By Brian on Nov 06, 2009 with Comments 1
When a user submits their email address in a form, you want to be sure it is a real email address. We will use the function preg_match() to see if it matches our regex for emails.
<?php
// Validate.php
function check_email($email){
$email = trim($email);
if(preg_match("/^[a-z0-9&'\.\-_\+]+@[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is", $email)){
// the email address matches our regex, now make sure it is valid
// we will split the email into 2 parts to make it easier to check for domain/ip
list($user,$domain) = split("@",$email);
if(!checkdnsrr($domain,"MX")){
return false;
} else {
return true;
}
} else {
return false;
}
}
?>
You can submit the email to this function using something like this:
<?php
$email_validation = check_email($_POST["email"]);
if($email_validation === true){
echo "Valid email, continue.";
} else {
echo "Invalid email, stop!";
}
?>
It is that simple!
Enjoy.
0
Popularity: 1% [?]
Filed Under: Web Programming

Thank you for the recommendation! I’ll give it a try.