PHP Validate Email Address

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% [?]

0saves
If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

Filed Under: Web Programming

Tags:

RSSComments (1)

Leave a Reply | Trackback URL

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

Leave a Reply




If you want a picture to show with your comment, go get a Gravatar.

The tutorials and scripts found on bgallz.org are for training purposes only, use to your discretion.