php verify email codes

Discussion in 'PHP' started by fafa7080, Nov 10, 2008.

  1. #1
    hi every one
    after searching google i find 4 codes which is for verifyng the email addresses which does the 3 processes for
    1) check whether the user has entered email address correctly
    (does not miss @ or .)
    2) check the domain whether it exists
    3) check the email address whether its exists or not
    iam a newbie in php ,so i dont know which of these codes work properly
    can anyone check please, i want to look like the website
    www.verify-email.org
    i want the functions in the code do the same process as the site i mentioned
    can anyone help me to modift the code like the website?
    code #1
    <script language="php">
    require("validEmail.php"); // your favorite here
    function testEmail($email)
    {echo $email;
      $pass = validEmail($email);
      if ($pass)
      {
        echo " is valid.\n";
      }
      else
      {
        echo " is not valid.\n";
      }
      return $pass;
    }
    $pass = true;
    echo "All of these should succeed:\n";
    $pass &= testEmail("dclo@us.ibm.com");
    $pass &= testEmail("abc\\@def@example.com");
    $pass &= testEmail("abc\\\\@example.com");
    $pass &= testEmail("Fred\\ Bloggs@example.com");
    $pass &= testEmail("Joe.\\\\Blow@example.com");
    $pass &= testEmail("\"Abc@def\"@example.com");
    $pass &= testEmail("\"Fred Bloggs\"@example.com");
    $pass &= testEmail("customer/department=shipping@example.com");
    $pass &= testEmail("\$A12345@example.com");
    $pass &= testEmail("!def!xyz%abc@example.com");
    $pass &= testEmail("_somename@example.com");
    $pass &= testEmail("user+mailbox@example.com");
    $pass &= testEmail("peter.piper@example.com");
    $pass &= testEmail("Doug\\ \\\"Ace\\\"\\ Lovell@example.com");
    $pass &= testEmail("\"Doug \\\"Ace\\\" L.\"@example.com");
    echo "\nAll of these should fail:\n";
    $pass &= !testEmail("abc@def@example.com");
    $pass &= !testEmail("abc\\\\@def@example.com");
    $pass &= !testEmail("abc\\@example.com");
    $pass &= !testEmail("@example.com");
    $pass &= !testEmail("doug@");
    $pass &= !testEmail("\"qu@example.com");
    $pass &= !testEmail("ote\"@example.com");
    $pass &= !testEmail(".dot@example.com");
    $pass &= !testEmail("dot.@example.com");
    $pass &= !testEmail("two..dot@example.com");
    $pass &= !testEmail("\"Doug \"Ace\" L.\"@example.com");
    $pass &= !testEmail("Doug\\ \\\"Ace\\\"\\ L\\.@example.com");
    $pass &= !testEmail("hello world@example.com");
    $pass &= !testEmail("gatsby@f.sc.ot.t.f.i.tzg.era.l.d.");
    echo "\nThe email validation ";
    if ($pass)
    {
       echo "passes all tests.\n";
    }
    else
    {
       echo "is deficient.\n";
    }
    
    /**
    Validate an email address.
    Provide email address (raw input)
    Returns true if the email address has the email
    address format and the domain exists.
    */
    function validEmail($email)
    {
       $isValid = true;
       $atIndex = strrpos($email, "@");
       if (is_bool($atIndex) && !$atIndex)
       {
          $isValid = false;
       }
       else
       {
          $domain = substr($email, $atIndex+1);
          $local = substr($email, 0, $atIndex);
          $localLen = strlen($local);
          $domainLen = strlen($domain);
          if ($localLen < 1 || $localLen > 64)
          {
             // local part length exceeded
             $isValid = false;
          }
          else if ($domainLen < 1 || $domainLen > 255)
          {
             // domain part length exceeded
             $isValid = false;
          }
          else if ($local[0] == '.' || $local[$localLen-1] == '.')
          {
             // local part starts or ends with '.'
             $isValid = false;
          }
          else if (preg_match('/\\.\\./', $local))
          {
             // local part has two consecutive dots
             $isValid = false;
          }
          else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
          {
             // character not valid in domain part
             $isValid = false;
          }
          else if (preg_match('/\\.\\./', $domain))
          {
             // domain part has two consecutive dots
             $isValid = false;
          }
          else if
    (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',
                     str_replace("\\\\","",$local)))
          {
             // character not valid in local part unless
             // local part is quoted
             if (!preg_match('/^"(\\\\"|[^"])+"$/',
                 str_replace("\\\\","",$local)))
             {
                $isValid = false;
             }
          }
    if ($isValid && !((checkdnsrr($domain,"MX")) ||
    (checkdnsrr($domain,"A"))))
          {
             // domain not found in DNS
             $isValid = false;
          }
       }
       return $isValid;
    }
    
    </script>
    
    
    Code (markup):

    code number 2)
      //    
        // Name: MEL :: Better Check Email Funct
        //     ion
        // Description:**UPDATED** This function
        //     will double check and validate an E-mail
        //     address by checking the sintaxis first a
        //     nd the domain's MX, A and CNAME records
        //     to be valid and active. It will return T
        //     RUE if the email is valid or FALSE if no
        //     t, very simple. The best approach I've m
        //     ade to validate an Email. Let me know th
        //     is has been useful, your comments and su
        //     ggestions are very much appreciate it. *
        //     *Please Vote**
        // By: Melvin D. Nava
        //
        // Assumes:Relies on the checkdnsrr PHP
        //     Function to do the DNS work. Not availab
        //     le for Windows. I've included a replacem
        //     ent (ONLY WIN32)
        //
        //This code is copyrighted and has    // limited warranties.Please see http://
        //     www.Planet-Source-Code.com/vb/scripts/Sh
        //     owCode.asp?txtCodeId=1316&lngWId=8    //for details.    //**************************************
        //    
       
        <?php
        //
        // CHECK EMAIL FUNCTION
        //***********************
        function check_email_mx($email) {
            if( (preg_match('/(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/', $email)) ||
                (preg_match('/^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/',$email)) ) {
                $host = explode('@', $email);
                if(checkdnsrr($host[1].'.', 'MX') ) return true;
                if(checkdnsrr($host[1].'.', 'A') ) return true;
                if(checkdnsrr($host[1].'.', 'CNAME') ) return true;
            }
            return false;
        }
        //
        //EXAMPLE
        //***********************
        if (check_email_mx("bill.gates@linux.com")) {
            echo "<p><font color=blue>";
            echo "<p>Email is valid, domain exists and has a valid MX host";
            echo "</font>";
        } else {
            echo "<p><font color=red>";
            echo "Either your email is not valid, domain doesn't exists or there is no valid MX host available";
            echo "</font>";
        }
        //
        // FIX FOR WINDOWS
        // PROGRAMMERS
        //***********************
        // checkdnsrr is not available
        // under windows I so included
        // the next replacement. You
        // may remove this if you are
        // gonna publish later over
        // any Linux/Unix OS
        //
        // thanx Jon Kriek for next snippet
        // and Rickard Sjo"quist for notice
        // Melvin D. Nava.
        //
        if (!function_exists('checkdnsrr')) {
            function checkdnsrr($host, $type = '') {
                if(!empty($host)) {
                    if($type == '') $type = "MX";
                    @exec("nslookup -type=$type $host", $output);
                    while(list($k, $line) = each($output)) {
                        if(eregi("^$host", $line)) {
                            return true;
                        }
                    }
                    return false;
                }
            }
        }
        ?>
    Code (markup):

    code number3)
    <?php
    /*
       $Id: VerifyEmailAddress.php 8 2008-01-13 22:51:10Z visser $
      
       Email address verification with SMTP probes
       Dick Visser <dick@tienhuis.nl>
    
       INTRODUCTION
    
       This function tries to verify an email address using several tehniques,
       depending on the configuration.
    
       Arguments that are needed:
    
       $email (string)
       The address you are trying to verify
    
       $domainCheck (boolean)
       Check if any DNS MX records exist for domain part
    
       $verify (boolean)
       Use SMTP verify probes to see if the address is deliverable.
    
       $probe_address (string)
       This is the email address that is used as FROM address in outgoing
       probes. Make sure this address exists so that in the event that the
       other side does probing too this will work.
      
       $helo_address (string)
       This should be the hostname of the machine that runs this site.
    
       $return_errors (boolean)
       By default, no errors are returned. This means that the function will evaluate
       to TRUE if no errors are found, and false in case of errors. It is not possible
       to return those errors, because returning something would be a TRUE.
       When $return_errors is set, the function will return FALSE if the address
       passes the tests. If it does not validate, an array with errors is returned.
    
    
       A global variable $debug can be set to display all the steps.
    
    
       EXAMPLES
    
       Use more options to get better checking.
       Check only by syntax:  validateEmail('dick@tienhuis.nl')
       Check syntax + DNS MX records: validateEmail('dick@tienhuis.nl', true);  
       Check syntax + DNS records + SMTP probe:
       validateEmail('dick@tienhuis.nl', true, true, 'postmaster@tienhuis.nl', 'outkast.tienhuis.nl');
    
    
       WARNING
     
       This function works for now, but it may well break in the future.
    
    */
    function validateEmail($email, $domainCheck = false, $verify = false, $probe_address='', $helo_address='', $return_errors=false) {
        global $debug;
        $server_timeout = 180; # timeout in seconds. Some servers deliberately wait a while (tarpitting)
        if($debug) {echo "<pre>";}
        # Check email syntax with regex
        if (preg_match('/^([a-zA-Z0-9\._\+-]+)\@((\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,7}|[0-9]{1,3})(\]?))$/', $email, $matches)) {
            $user = $matches[1];
            $domain = $matches[2];
            # Check availability of DNS MX records
            if ($domainCheck && function_exists('checkdnsrr')) {
                # Construct array of available mailservers
                if(getmxrr($domain, $mxhosts, $mxweight)) {
                    for($i=0;$i<count($mxhosts);$i++){
                        $mxs[$mxhosts[$i]] = $mxweight[$i];
                    }
                    asort($mxs);
                    $mailers = array_keys($mxs);
                } elseif(checkdnsrr($domain, 'A')) {
                    $mailers[0] = gethostbyname($domain);
                } else {
                    $mailers=array();
                }
                $total = count($mailers);
                # Query each mailserver
                if($total > 0 && $verify) {
                    # Check if mailers accept mail
                    for($n=0; $n < $total; $n++) {
                        # Check if socket can be opened
                        if($debug) { echo "Checking server $mailers[$n]...\n";}
                        $connect_timeout = $server_timeout;
                        $errno = 0;
                        $errstr = 0;
                        # Try to open up socket
                        if($sock = @fsockopen($mailers[$n], 25, $errno , $errstr, $connect_timeout)) {
                            $response = fgets($sock);
                            if($debug) {echo "Opening up socket to $mailers[$n]... Succes!\n";}
                            stream_set_timeout($sock, 30);
                            $meta = stream_get_meta_data($sock);
                            if($debug) { echo "$mailers[$n] replied: $response\n";}
                            $cmds = array(
                                "HELO $helo_address",
                                "MAIL FROM: <$probe_address>",
                                "RCPT TO: <$email>",
                                "QUIT",
                            );
                            # Hard error on connect -> break out
                            # Error means 'any reply that does not start with 2xx '
                            if(!$meta['timed_out'] && !preg_match('/^2\d\d[ -]/', $response)) {
                                $error = "Error: $mailers[$n] said: $response\n";
                                break;
                            }
                            foreach($cmds as $cmd) {
                                $before = microtime(true);
                                fputs($sock, "$cmd\r\n");
                                $response = fgets($sock, 4096);
                                $t = 1000*(microtime(true)-$before);
                                if($debug) {echo htmlentities("$cmd\n$response") . "(" . sprintf('%.2f', $t) . " ms)\n";}
                                if(!$meta['timed_out'] && preg_match('/^5\d\d[ -]/', $response)) {
    
                                    $error = "Unverified address: $mailers[$n] said: $response";
                                    break 2;
                                }
                            }
                            fclose($sock);
                            if($debug) { echo "Succesful communication with $mailers[$n], no hard errors, assuming OK";}
                            break;
                        } elseif($n == $total-1) {
                            $error = "None of the mailservers listed for $domain could be contacted";
                        }
                    }
                } elseif($total <= 0) {
                    $error = "No usable DNS records found for domain '$domain'";
                }
            }
        } else {
            $error = 'Address syntax not correct';
        }
        if($debug) { echo "</pre>";}
       
        if($return_errors) {
            # Give back details about the error(s).
            # Return FALSE if there are no errors.
            if(isset($error)) return htmlentities($error); else return false;
        } else {
            # 'Old' behaviour, simple to understand
            if(isset($error)) return false; else return true;
        }
    }
    
    ?>
    
    Code (markup):

     
    fafa7080, Nov 10, 2008 IP
  2. fafa7080

    fafa7080 Member

    Messages:
    37
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #2
    code # 4)
    <?php
    /*
    Originally
    By: Jon S. Stevens jon@clearink.com
    Copyright 1998 Jon S. Stevens, Clear Ink
    This code has all the normal disclaimers.
    It is free for any use, just keep the credits intact.
    
    Enacements and modifications:
    
    By: Shane Y. Gibson shane@tuna.org
    Organization: The Unix Network Archives (http://www.tuna.org./)
    Date: November 16th, 1998
    Changes: Added **all** comments, as original code lacked them.
    Added some return codes to include a bit more description
    for useability.
    
    By : berber
    Organization : webdev.berber.co.il
    Date : April 10th, 1999
    Changes : The script now handls all kind of domains (not only @xxx.yyy) as before.
    Added a debuging mode which also works as a verbose mode.
    
    */
    
    /* This function takes in an email address (say 'shane@tuna.org')
    * and tests to see if it's a valid email address.
    *
    * An array with the results is passed back to the caller.
    *
    * Possible result codes for the array items are:
    *
    * Item 0: [true|false] true for valid email address
    * false for NON-valid email address
    *
    * Item 1: [SMTP Code] if a valid MX mail server found, then
    * fill this array in with failed SMTP
    * reply codes
    *
    * Item 2: [true|false] true for valid mail server found for
    * host/domain
    * false if no valid mail server found
    *
    * Item 3: [MX server] if a valid MX host was found and
    * connected to then fill in this item
    * with the MX server hostname
    *
    * EXAMPLE code for use is at the very end of this function.
    */
    
    function validateEmail ( $email )
    {
    $debug_=0;
    // used for SMTP HELO argument
    global $SERVER_NAME;
    
    // initialize our return array, populating with default values
    $return = array ( false, "", "", "" );
    
    // assign our user part and domain parts respectively to seperate // variables
    list ( $user, $domain ) = split ( "@", $email, 2 );
    if($debug_==1) {
            echo"user: $user<BR>";
            echo"domain: $domain<BR>";
    }
    // split up the domain name into sub-parts
    $arr = explode ( ".", $domain );
    
    // figure out how many parts to the host/domain name portion there are
    $count = count ( $arr );
    
    // get our Top-Level Domain portion (i.e. foobar.org)
    $tld = $arr[$count - 2] . "." . $arr[$count - 1];
    
    // check that an MX record exists for Top-Level Domain, and if so
    // start our email address checking
    if ( checkdnsrr ( $domain, "MX" ) )
    {
            if($debug_==1) {
             echo"Check DNS RR OK<BR>";
            }
    // Okay...valid dns reverse record; test that MX record for
    // host exists, and then fill the 'mxhosts' and 'weight'
    // arrays with the correct information
    //
    if ( getmxrr ( $domain, $mxhosts, $weight ) )
    {
    if($debug_==1) {
                    echo "MX LOOKUP RESULTS :<BR>";
    
                    for ( $i = 0; $i < count ( $mxhosts ); $i++ ) {
                            echo "??????o $mxhosts[$i]<BR>";
                    }
             }
    
             // sift through the 'mxhosts' connecting to each host
    
    for ( $i = 0; $i < count ( $mxhosts ); $i++ )
    {
    // open socket on port 25 to mxhosts, setting // returned file pointer to the  variable 'fp'
    
    $fp = fsockopen ( $mxhosts[$i], 25 );
    // if the 'fp' was set, then goto work
    if ($fp)
    {
                     if($debug_==1) {
                            echo"Socket Opened successfully<BR>";
                     }
    // work variables
    $s = 0;
    $c = 0;
    $out = "";
    
    // set our created socket for 'fp' to
    // non-blocking mode
    // so our fgets() calls will return
    // right away
    set_socket_blocking ( $fp, false );
    
    // as long as our 'out' variable has a
    // null value ("")
    // keep looping (do) until we get
    // something
    //
    do
    {
    // output of the stream assigned
    // to 'out' variable
    $out = fgets ( $fp, 2500 );
                            if($debug_==1) {
                             if($out != "") echo"out: $out<BR>";
                            }
    // if we get an "220" code (service ready code (i.e greeting))
    // increment our work (code (c)) variable, and null
    // out our output variable for a later loop test
    //
    if ( ereg ( "^220", $out ) )
    {
                             if($debug_==1) {
                                    echo"service ready on recipient machine.<BR>";
                             }
    $s = 0;
    $out = "";
    $c++;
    $return[2] = true;
    $return[3] = $mxhosts[$i];
    }
    // elseif c is greater than 0
    // and 'out' is null (""),
    // we got a code back from some
    // server, and we've passed
    // through this loop at least
    // once
    //
    else if (($c > 0) && ($out == ""))
    {
                             if($debug_==1) {
    echo"OK so far Breaking...<BR>";
    }
    $return[2] = true;
    break;
    }
    
    // else increment our 's'
    // counter
    else
    { $s++; }
    
    // and if 's' is 9999, break, to
    // keep from looping
    // infinetly
    if ( $s == 9999 ) {
                             if($debug_==1) {
    echo"Reached maximum 10000 loops, breaking.<BR>";
    }       
                             break;
                            }
    
    } while ( $out == "" );
    
    // reset our file pointer to blocking
    // mode, so we wait
    // for communication to finish before
    // moving on...
    set_socket_blocking ( $fp, true );
    
    // talk to the MX mail server,
    // validating ourself (HELO)
    fputs ( $fp, "HELO $SERVER_NAME\n" );
                     if($debug_==1) {
    echo"<BR><BR>HELO $SERVER_NAME<BR>";
    }
    // get the mail servers reply, assign to
    // 'output' (ignored)
    $output = fgets ( $fp, 2000 );
                   
             // give a bogus "MAIL FROM:" header to
    // the server
    fputs ( $fp, "MAIL FROM: <info@" . $domain . ">\n" );
                     if($debug_==1) {
    echo"MAIL FROM: <info@" . $domain . "><BR>";
    }
    // get output again (ignored)
    $output = fgets ( $fp, 2000 );
    
    // give RCPT TO: header for the email
    // address we are testing
    fputs ( $fp, "RCPT TO: <$email>\n" );
                     if($debug_==1) {
    echo"RCPT TO: <$email><BR>";
    }
    // get final output for validity testing
    // (used)
    $output = fgets ( $fp, 2000 );
                     if($debug_==1) {
                            echo"output : $output<BR>";
                     }
    // test the reply code from the mail
    // server for the 250 (okay) code
    if ( ereg ( "^250", $output ) )
    {
    if($debug_==1) {
                            echo"Recipiant OK<BR>";
                     }
                            // set our true/false(ness)
    // array item for testing
    $return[0] = true;
    }
    else
    {
    // otherwise, bogus address,
    // fillin the 2nd array item
    // with the mail servers reply
    // code for user to test if they
    // want
    $return[0] = false;
    $return[1] = $output;
                            if($debug==1) {
                             echo"Bad Recipiant <BR>";
                            }
    }
    
    // tell the mail server we are done
    // talking to it
    fputs ( $fp, "QUIT\n" );
                     if($debug==1) {
                            echo"Quit";
                     }
    // close the file pointer
    fclose( $fp );
    
    // if we got a good value break,
    // otherwise, we'll keep
    // trying MX records until we get a good
    // value, or we
    // exhaust our possible MX servers
    if ($return[0] == true) {
                            if($debug_==1) {
                                    echo"Recipiant OK... Breaking";
                            }       
                            break;
                     }
    }
    }
    }
    } else {
    // No MX record appears for the specified Top-Level Domain; possibly
    // an invalid host/domain name was specified.
    $return[0] = false;
    $return[1] = "Invalid email address (bad domain name)";
    $return[2] = false;
    } // end if checkdnsrr()
    
    // return the array for the user to test against
    return $return;
    }
    ?>
    
    <?php
    // Here is an example chunk of code... Normally, you'd call the
    // validate email with a form or some other method to provide
    // the input email address
    //
    // NOTE: You need to delete the /* and */ comment entries
    
    /*
    // Minimal HTML code to test validateEmail() function. Save this
    // to a file to test...try different email addresses in the
    // 'email_address' variable field to see how it behaves.
    //
    <html>
    <head>
    <tilte> Validate an email address. </title>
    </head>
    
    <body bgcolor="#000000" TEXT="#FFFFCC" LINK="#33CCFF" VLINK="#9999CC" ALINK="#FFFF00">
    
    // Assumes that you put the validateEmail() function in a file
    // named "validateEmail.php3", which is in the current directory
    <?php include( "validateEmail.php3" );
    
    $email_address = "shane@tuna.org";
    $val_results = array( "", "" );
    
    $val_results = validateEmail( $email_address );
    
    if ( $val_results[0] == true )
    {
    $value = "<font color=\"green\">a valid</font>";
    } else {
    $value = "<font color=\"red\">not a valid</font>";
    }
    
    // print debugging info
    print( "<br>Debugging Info:<br><br>" );
    print( "<pre>" );
    print( "(valid/not valid) <font color=\"white\">value</font> is: " . $value. "<br>");
    print( "(true/false valid email) <font color=\"white\">val_results[0]</font> is: " . $val_results
    [0] . "<br>");
    print( "(SMTP code if false) <font color=\"white\">val_results[1]</font> is: " . $val_results
    [1] . "<br>");
    print( "(true/false valid MX host) <font color=\"white\">val_results[2]</font> is: " .
    $val_results[2] . "<br>");
    print( "(MX host that answered) <font color=\"white\">val_results[3]</font> is: " . $val_results
    [3] . "<br>");
    print( "</pre>" );
    print( "<pre>true is represented by a 1 (one)<br>false is represented by null output</pre><br>");
    // end debugging info
    
    print( "The address <font color=\"white\"><tt>" . $email_address . "</tt></font> is " .
    $value . " email address.");
    */
    
    ?>
    
    </body>
    </html>
    Code (markup):
     
    fafa7080, Nov 10, 2008 IP
  3. intelrate

    intelrate Peon

    Messages:
    31
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    I can suggest this function for step 1) of your task:

    
    public function isEmail($input)
    {
        return eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $input);
    }
    
    PHP:
     
    intelrate, Nov 10, 2008 IP
  4. fafa7080

    fafa7080 Member

    Messages:
    37
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #4
    hi thanks 4 the reply
    i want all the task together in a one php file to work properly
    anyone knows php??? to make his work
     
    fafa7080, Nov 10, 2008 IP