×
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!
  • Students Click Here

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

Jobs

Parsing

How do I validate an email address? by sleipnir214
Posted: 5 Sep 02 (Edited 8 Jul 03)

<?php

/*
    This function checks an email address to determine whether it is valid.
    
    It takes an email address as its first input parameter and determines whether
    the address is well-formed.  The definition of a well-formed address is based
    on RFC2821, but may vary from the strict definition.
    
        A well formed SMTP email address is made up of a username, followed by
        exactly one "@"-symbol, followed by a domain.
        
        A username begins with a digit or letter, and can be followed by any
        number of digits, letters, dots, dashes, and underscores.
        
        A domain begins with a digit or letter, and is followed by any number
        of digits, letters, dots and dashes.  A domain must contain at least one
        dot to be well-formed.
        
    
    If the function determines an address is well-formed, it can then optionally
    determine whether the domain part of the address ends in a known Top-Level
    Domain (TLD).  This option is turned on by setting the second input parameter
    to any value that does not explicitly equal FALSE.  The list of known TLDs
    are stored in the array $tld_match_array and are accurate as of 2002-09-05.
    
    Note:    This function does not take into account the inherent weirdness of
            the ".us" TLD.
    
    
    LICENSE:
    Do whatever you want with this code.
    
    WARRANTY:
    This code comes with no warranty as to the safety or accuracy of its
    operation.  Use with circumspection and trepidation.  If it breaks
    something, I recommend vituperation.

*/

function good_email ($address, $validate_tld = FALSE)
{
    $retval = TRUE;

    /*
        A list of known good TLDs.
        This data from http://www.uwhois.com/domains.html and
        http://www.icann.org/tlds .  This data accurate as of
        2003-07-08.
    */

    $tld_matches  = '/\.(';
    $tld_matches .= 'ac|ac\.at|ac\.cn|ac\.id|ac\.jp|ac\.kr|ac\.nz|ac\.uk|ad|';
    $tld_matches .= 'ad\.jp|ae|aero|af|al|am|an|an|ao|aq|as|at|aw|ba|bb|bd|';
    $tld_matches .= 'bd|be|bf|bf|bg|bi|biz|bj|bm|bn|bo|bs|bt|bv|bw|by|bz|ca|';
    $tld_matches .= 'cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|co\.at|co\.az|co\.hu|';
    $tld_matches .= 'co\.id|co\.il|co\.jp|co\.kr|co\.nz|co\.tz|co\.uk|co\.uz|';
    $tld_matches .= 'co\.vi|co\.za|com|com\.ag|com\.ai|com\.ar|com\.au|com\.az|';
    $tld_matches .= 'com\.bb|com\.bh|com\.br|com\.bs|com\.cn|com\.do|com\.eg|';
    $tld_matches .= 'com\.gy|com\.hm|com\.kz|com\.mt|com\.mx|com\.nf|com\.pa|';
    $tld_matches .= 'com\.pe|com\.pn|com\.pr|com\.ru|com\.sc|com\.sg|com\.ua|';
    $tld_matches .= 'coop|cr|cri\.nz|cu|cv|cv|cx|cy|cz|de|dj|dk|dm|dz|ec|edu|';
    $tld_matches .= 'edu\.au|edu\.tw|ee|er|es|et|eun\.eg|fi|fj|fk|fm|fo|fr|ga|';
    $tld_matches .= 'gd|ge|gen\.nz|gf|gg|gh|gi|gl|gm|gn|gob\.mx|gov|gov\.au|';
    $tld_matches .= 'govt\.nz|gp|gq|gr|gr\.jp|gs|gt|gu|gw|hk|hn|hr|ht|id|ie|im|';
    $tld_matches .= 'in|ind\.br|inf\.br|info|int|iq|ir|is|it|iwi\.nz|je|jm|jo|';
    $tld_matches .= 'ke|kg|kh|ki|km|kn|kw|ky|la|lb|lc|li|lk|lr|ls|lt|ltd\.uk|';
    $tld_matches .= 'lu|lv|ly|ly|ma|maori\.nz|mc|md|mg|mh|mil|mil\.nz|mk|ml|mm|';
    $tld_matches .= 'mn|mo|mp|mq|mr|ms|mu|museum|mv|mw|my|mz|na|name|nc|ne|';
    $tld_matches .= 'ne\.jp|net|net\.ae|net\.ar|net\.au|net\.bb|net\.br|';
    $tld_matches .= 'net\.bs|net\.cn|net\.eg|net\.lu|net\.mx|net\.nz|net\.ru|';
    $tld_matches .= 'net\.tw|net\.uk|ng|ni|nl|no|np|nr|nu|om|or\.jp|org|';
    $tld_matches .= 'org\.ae|org\.ar|org\.bb|org\.bs|org\.cn|org\.il|org\.lu|';
    $tld_matches .= 'org\.nz|org\.uk|pf|pg|ph|pk|pl|plc\.uk|pm|pro|pt|pw|py|qa|';
    $tld_matches .= 're|ro|ru|rw|sa|sb|school\.nz|sd|se|sh|si|si|sj|sk|sl|sm|';
    $tld_matches .= 'sn|so|sr|st|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|';
    $tld_matches .= 'tv|ug|um|us|uy|va|vc|ve|vg|vn|vu|ws|ye|yu|zm|zr|zw';
    $tld_matches .= ')$/';


    //First, split the address a the "@"-symbol into the username and domain name parts
    $address_array = preg_split ('/@/', $address);
                                                            
    //Was exactly one "@" found?
    if (sizeof ($address_array) != 2)
    {
        $retval = FALSE;
    }
    
    if ($retval === TRUE)
    {
        //Store the user and domain parts in more readable variables.
        list($user, $domain) = $address_array;

        //Split the user-name part of the address at any dots
        $user_array = preg_split ('/\./', $user);
        
        //Check each piece for well-formedness
        for ($counter = 0;
             $counter < sizeof($user_array) && $retval == TRUE;
             $counter++)
        {
            if (!preg_match ('/^[a-z0-9\-_]+$/i', $user_array[$counter]))
            {
                $retval = FALSE;
            }
        }
    }
        
    if ($retval === TRUE)
    {
        //split the domain part of the address at any dots in it
        $domain_array = preg_split ('/\./', $domain);
            
        //Did the domain part contain at least one dot
        //(making two array variables)?
        if (sizeof($domain_array) > 1)
        {
            //Is each part of the domain well-formed? Stop checking if
            //any part is not
            $domain_value = TRUE;
            for ($counter = 0;
                 $counter < sizeof($domain_array) && $domain_value === TRUE;
                 $counter++)
            {
                if (!preg_match ('/^[a-z0-9]+([a-z0-9\-]*[a-z0-9]+)*$/i', $domain_array[$counter]))
                {
                    $domain_value = FALSE;
                }
            }
            $retval = $domain_value;
                
            //if the domain part has passed all tests so far and the function
            //has been instructed to validate the TLD...
            if ($retval === TRUE && $validate_tld !== FALSE)
            {
                if (!preg_match ($tld_matches, $domain))
                {
                    $retval = FALSE;
                }
            }
        }
    }
    
    return $retval;
}



//Below is some PHP code which will drive the function.


print '
<html>
<body>
<table border=0>
    <form method=post action="'.$PHP_SELF.'">
    <tr>
        <td align=right>Email address:</td>
        <td align=left>
            <input type=text name=address value="';

if (array_key_exists('address', $_POST))
{
    print $_POST[address];
}

print '">
        </td>
    </tr>
    <tr>
        <td align=right>Validate TLD?</td>
        <td align=left>
            <input type=checkbox name=check_tld';
print array_key_exists('check_tld', $_POST)?' checked':'';
print '>
        </td>
    </tr>
    <tr>
        <td colspan=2 align=center>
            <input type=submit>
        </td>
    </tr>
    </form>
    <tr>
        <td colspan=2 align=center>';

if (array_key_exists("address", $_POST))
{
    $result = good_email ($_POST[address],
                          (array_key_exists('check_tld', $_POST)?TRUE:FALSE)
                         );

    print "'$_POST[address]' ";
        
    if ($result === TRUE)
    {
        print 'Good';
    }
    else
    {
        print 'Bad';
    }
}
else
{
    print "รก";
}    

print '
        </td>
    </tr>
</table>
</body>
</html>';
?>

Back to PHP FAQ Index
Back to PHP Forum

My Archive

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close