Version: 1.04

Type: Sample Code (HOWTO)

Category: Other

License: GNU General Public License

Description: How to validate an email? Some use lots of lines with string functions. Following lines work fine to validate the format at a first stage. Just 1 line. It could be completed by comparing the last part of the email (last dot) with a database containing all valid extensions (.com,.edu,.fr,.ag,...).



<?php 
/*
Email Syntax & Valid Domain (MX) Check.
Script developed by Bonnie Kinship on Thu, Jan 08, 2004 @ 05:10PM.
The script is tested and verfied. Performance is found OK.
If you find this script useful, Feel free to use & modify per your requirements.
No restrictions on using this script.

Purpose: To screen bogus or fake email address inputs.

The script validates email addresses for syntax and checks against MX records of the domain.

for Example: 

1) email address like user@mailprovider.com will pass syntax check, 
but fail for domain MX records.

2) email address like user123xyz@yahoo.com will pass in both, but in fact email account
user123xyz may not exist on yahoo mail server.

Conclusion:
This script helps to prevent website visitor to provide bogus email address inputs upto
certain extent. At the time of writing this we are testing SMTP Class.
But, even SMTP Class is not sure shot & proven way to validate email addresses.

As such there is only one proven way to make sure if email address is valid or not is to send
an actual email to the email address provided by site visitor. That's why many web-site send 
email confirmation. 
*/

// You can use email address from input field from the form by using GET or POST method.
$email = "user@mailprovider.com";  

//------------ EMAIL ADDRESS SYNTAX CHECK ------------------------------------------------
if (!eregi("^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,6})$", $email)) { 
        print ("Syntax Error!. Email Address $email does not match valid syntax criteria!");
        exit;
}
//------------ DOMAIN "MX" RECORDS CHECK -------------------------------------------------- 
    list ( $user, $domain ) = split ("@",$email,2); 
    if ( (!checkdnsrr ( $domain, "MX" )) || (!checkdnsrr ( $domain, "ANY" )) || (!getmxrr ($domain, $MXHost)))  { 
        print ("Error: No user records found for User: $user on Domain: $domain.<BR>");
        print ("Please go-back & provide us a vallid email address!");
        exit;
}
exit;
?>