Home » Code

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

Share/Bookmark this!

One Comment

Leave a reply

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally recognized avatar, please register at Gravatar.

Side Notes

This entry was posted by on November 6, 2009 at 2:29 PM and filed under Code category.

You can add your comments or trackback from your own site. To keep you updated to the latest discussion, you can subscribe to these comments via RSS.

Recent Entries

Pages

Recent Comments

Resources

Questions & Answers

Just started! Have not answered any questions.

Tag Cloud

background body CSS database date dropdown email error_reporting favicon file filesize form format function global hosting HTML image Javascript limit link linkbar mysql numbers online option ordinalize pagination pattern photoshop PHP resize rows script search snowing stylesheet switch table thumbnail time timestamp upload validate variables

Sponsors