Best e-mail verification ever?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
slimsam1
Forum Commoner
Posts: 49
Joined: Wed Aug 21, 2002 12:20 am

Best e-mail verification ever?

Post by slimsam1 »

I'm on a mission to find/write/derive the best e-mail address verification possible.

Here's what I have so far; keep in mind that I want to avoid the MX check if the email address isn't in the correct form in the first place (that's why I have a nested "if" instead of one).


Code: Select all

<?php
	function verifyEmail($emailAddress)
	{
		if (ereg("^[a-zA-Z0-9_\.]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$", $emailAddress)){
			$emailArray = explode("@",$emailAddress);
			if (checkdnsrr($emailArray[1])){
				return TRUE;
			} else {
				return FALSE;
			}
		} else {
			return FALSE;
		}
	}
?>
(edit) I just thought of a way to shorten it:

Code: Select all

<?php
	function verifyEmail($emailAddress)
	{
		if (ereg("^[a-zA-Z0-9_\.]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$", $emailAddress)){
			$emailArray = explode("@",$emailAddress);
			if (checkdnsrr($emailArray[1])){
				return TRUE;
			}
		}
		return FALSE;
	}
?>
User avatar
mikusan
Forum Contributor
Posts: 247
Joined: Thu May 01, 2003 1:48 pm

Post by mikusan »

Here is an even shorter way that I commonly use:

Code: Select all

if( eregi( "^[a-z0-9]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*.[a-z]{2,3}$", $email ))
    {
        return TRUE;
    }
    else 
    {
        return FALSE;
    }
CyberSpatium
Forum Newbie
Posts: 21
Joined: Thu Mar 20, 2003 12:23 pm
Contact:

Post by CyberSpatium »

Here is your code formated into a class.

Code: Select all

# email class to check for valid email address strings
	class email {
		
		# get email patern
		var $emailpattern =  "^[a-z0-9]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*.[a-z]{2,3}$";
	
		# check for valid email function
		function checkemail ($emailaddr) {
	
			# test if email is valid, and return results
			if( eregi($this->emailpattern, $emailaddr)) { 
				
				# email verified, setup to check dns
				$emailarray = explode("@", $emailaddr); 
					
				# verify email dns exists
				if (checkdnsrr($emailarray[1])) { 
					return TRUE;
				}
			
			} else {
			
				return FALSE;
			
			} # end if eregi

		} # end check email function

	} # end email class


/*

	SAMLPE USAGE OF CHECK EMAIL CLASS

	$email = new email;
	$check = $email->checkemail($email);

	if (!$check) {
		print ("That email address is invalid.\n");
		exit;
	}

*/
Cyber
slimsam1
Forum Commoner
Posts: 49
Joined: Wed Aug 21, 2002 12:20 am

Post by slimsam1 »

CyberSpatium wrote:Here is your code formated into a class.

...
Cyber
There is a problem with this. Let's say the email passed the syntax check but not the MX record lookup. You wouldn't be returning FALSE... it would just not return anything. That's why I put the return FALSE outside of any "if" or "else". In the case that the email fals the syntax check or the MX lookup, it will simply return false, and since the return TRUE terminates the execution of the rest of the function, it is not necessary to "skip over" the return FALSE with an else.

By the way, I have a much better regular expression now:

Code: Select all

class verify
&#123;

 
	function email($emailAddress)
	&#123;      
		if (preg_match('/&#1111;^\x00-\x20()<>@,;:&quote;.&#1111;\]\x7f-\xff]+(?:\.&#1111;^\x00-\x20()<>@,;:&quote;.&#1111;\]\x7f-\xff]+)*\@&#1111;^\x00-\x20()<>@,;:&quote;.&#1111;\]\x7f-\xff]+(?:\.&#1111;^\x00-\x20()<>@,;:&quote;.&#1111;\]\x7f-\xff]+)+/i', $emailAddress))&#123;
        		$emailArray = explode("@",$emailAddress);
         		if (checkdnsrr($emailArray&#1111;1]))&#123;
            			return TRUE;
        		&#125;
		&#125;
		return FALSE; 
	&#125;
&#125;
I find commenting every single line slightly annoying.
slimsam1
Forum Commoner
Posts: 49
Joined: Wed Aug 21, 2002 12:20 am

Post by slimsam1 »

mikusan wrote:Here is an even shorter way that I commonly use:

Code: Select all

if( eregi( "^[a-z0-9]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*.[a-z]{2,3}$", $email ))
    {
        return TRUE;
    }
    else 
    {
        return FALSE;
    }
The idea behind mine is that after the syntax is checked, the server does an actual check to see if the domain exists and is capable of recieving email. That's what the checkdnsrr() function is for.
:)
slimsam1
Forum Commoner
Posts: 49
Joined: Wed Aug 21, 2002 12:20 am

Post by slimsam1 »

liljester wrote:i think if it doesnt return anything, it is interpreted as false... Please, someone smack me if im wrong.
Well, that's certainly possible, but if that's the case, then I don't need any return FALSE's :)

(edit- you deleted your post! :x )
Last edited by slimsam1 on Thu May 22, 2003 1:45 pm, edited 1 time in total.
User avatar
liljester
Forum Contributor
Posts: 400
Joined: Tue May 20, 2003 4:49 pm

Post by liljester »

indeed =)
slimsam1
Forum Commoner
Posts: 49
Joined: Wed Aug 21, 2002 12:20 am

Post by slimsam1 »

Does anyone have any ideas on how to improve this snippet of code even more? Aside from the coding style, that is. Any new things to add to further verify?
CyberSpatium
Forum Newbie
Posts: 21
Joined: Thu Mar 20, 2003 12:23 pm
Contact:

Post by CyberSpatium »

slimsam1 wrote:Does anyone have any ideas on how to improve this snippet of code even more? Aside from the coding style, that is. Any new things to add to further verify?
found this code in the code gallery at http://www.zend.com:
http://www.zend.com/codex.php?id=449&single=1

Code: Select all

/* ======================================================================= 
    
ifsnow's email valid check function SnowCheckMail Ver 0.1 
   
funtion SnowCheckMail ($Email,$Debug=false) 

$Email : E-Mail address to check. 
$Debug : Variable for debugging. 

* Can use everybody if use without changing the name of function. 

Reference : O'REILLY - Internet Email Programming 

HOMEPAGE : http://www.hellophp.com 

ifsnow is korean phper. Is sorry to be unskillful to English. *^^*;; 

========================================================================= */ 

function SnowCheckMail($Email,$Debug=false) 
{ 
    global $HTTP_HOST; 
    $Return =array();   
    // Variable for return. 
    // $Return[0] : [true|false] 
    // $Return[1] : Processing result save. 

    if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $Email)) { 
        $Return[0]=false; 
        $Return[1]="${Email} is E-Mail form that is not right."; 
        if ($Debug) echo "Error : {$Email} is E-Mail form that is not right.<br>";          
        return $Return; 
    } 
    else if ($Debug) echo "Confirmation : {$Email} is E-Mail form that is not right.<br>"; 

    // E-Mail @ by 2 by standard divide. if it is $Email this "lsm@ebeecomm.com".. 
    // $Username : lsm 
    // $Domain : ebeecomm.com 
    // list function reference : http://www.php.net/manual/en/function.list.php 
    // split function reference : http://www.php.net/manual/en/function.split.php 
    list ( $Username, $Domain ) = split ("@",$Email); 

    // That MX(mail exchanger) record exists in domain check . 
    // checkdnsrr function reference : http://www.php.net/manual/en/function.checkdnsrr.php 
    if ( checkdnsrr ( $Domain, "MX" ) )  { 
        if($Debug) echo "Confirmation : MX record about {$Domain} exists.<br>"; 
        // If MX record exists, save MX record address. 
        // getmxrr function reference : http://www.php.net/manual/en/function.getmxrr.php 
        if ( getmxrr ($Domain, $MXHost))  { 
      if($Debug) { 
                echo "Confirmation : Is confirming address by MX LOOKUP.<br>"; 
              for ( $i = 0,$j = 1; $i < count ( $MXHost ); $i++,$j++ ) { 
            echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Result($j) - $MXHost[$i]<BR>";   
        } 
            } 
        } 
        // Getmxrr function does to store MX record address about $Domain in arrangement form to $MXHost. 
        // $ConnectAddress socket connection address. 
        $ConnectAddress = $MXHost[0]; 
    } 
    else { 
        // If there is no MX record simply @ to next time address socket connection do . 
        $ConnectAddress = $Domain;          
        if ($Debug) echo "Confirmation : MX record about {$Domain} does not exist.<br>"; 
    } 

    // fsockopen function reference : http://www.php.net/manual/en/function.fsockopen.php 
    $Connect = fsockopen ( $ConnectAddress, 25 ); 

    // Success in socket connection 
    if ($Connect)    
    { 
        if ($Debug) echo "Connection succeeded to {$ConnectAddress} SMTP.<br>"; 
        // Judgment is that service is preparing though begin by 220 getting string after connection . 
        // fgets function reference : http://www.php.net/manual/en/function.fgets.php 
        if ( ereg ( "^220", $Out = fgets ( $Connect, 1024 ) ) ) { 
              
            // Inform client's reaching to server who connect. 
            fputs ( $Connect, "HELO $HTTP_HOST\r\n" ); 
                if ($Debug) echo "Run : HELO $HTTP_HOST<br>"; 
            $Out = fgets ( $Connect, 1024 ); // Receive server's answering cord. 

            // Inform sender's address to server. 
            fputs ( $Connect, "MAIL FROM: <{$Email}>\r\n" ); 
                if ($Debug) echo "Run : MAIL FROM: <{$Email}><br>"; 
            $From = fgets ( $Connect, 1024 ); // Receive server's answering cord. 

            // Inform listener's address to server. 
            fputs ( $Connect, "RCPT TO: <{$Email}>\r\n" ); 
                if ($Debug) echo "Run : RCPT TO: <{$Email}><br>"; 
            $To = fgets ( $Connect, 1024 ); // Receive server's answering cord. 

            // Finish connection. 
            fputs ( $Connect, "QUIT\r\n"); 
                if ($Debug) echo "Run : QUIT<br>"; 

            fclose($Connect); 

                // Server's answering cord about MAIL and TO command checks. 
                // Server about listener's address reacts to 550 codes if there does not exist   
                // checking that mailbox is in own E-Mail account. 
                if ( !ereg ( "^250", $From ) || !ereg ( "^250", $To )) { 
                    $Return[0]=false; 
                    $Return[1]="${Email} is address done not admit in E-Mail server."; 
                    if ($Debug) echo "{$Email} is address done not admit in E-Mail server.<br>"; 
                    return $Return; 
                } 
        } 
    } 
    // Failure in socket connection 
    else { 
        $Return[0]=false; 
        $Return[1]="Can not connect E-Mail server ({$ConnectAddress})."; 
        if ($Debug) echo "Can not connect E-Mail server ({$ConnectAddress}).<br>"; 
        return $Return; 
    } 
    $Return[0]=true; 
    $Return[1]="{$Email} is E-Mail address that there is no any problem."; 
    return $Return; 
}
Post Reply