PHP script t verify an email

I want to write a script which verifies the email address, and I how wrote the following script:
<?php
  $email="xxxx@xxxxxx.com";
  list($username,$domain)=split("@",$email);
  echo $domain."\n";
  $ip = gethostbyname($domain);
  $hostname = gethostbyaddr($ip);
  $hosts=checkdnsrr($domain, 'MX');
  echo $hosts."\n";
  echo $hostname."\n";
  echo $ip."\n";
?>

For google email I am getting:
google.com
1
mia05s08-in-f9.1e100.net
173.194.37.9

BUT for xxxxxxx.com:
xxxxxx.com

176.74.176.179
176.74.176.179

And for yyyyyyy.com:
yyyyyyy.com

62.116.143.21
62.116.143.21

How reliable is this check? I was expecting not to get anything in case of faulty domain, but I do, and I get as well the same answer in case of normal nslookup from the command line, and is there is any more strict script which can verify the email server?
P.S. I running this check from another email server.
Ashraf HassaneinAsked:
Who is Participating?
 
Ray PaseurConnect With a Mentor Commented:
"Faulty domain" is not really a good way of looking at this.  The domain address is either routable or not, and checkdnsrr() will tell you if it is routable.

Here is how I would verify an email address, in two steps.  First, is it well-formed and routable?
<?php // RAY_email_validation.php
error_reporting(E_ALL);


// A FUNCTION TO TEST FOR A VALID EMAIL ADDRESS, RETURN TRUE OR FALSE
// SEE MAN PAGE: http://php.net/manual/en/intro.filter.php
function check_valid_email($email, $rout=TRUE)
{
    // LIST OF BLOCKED DOMAINS
    $bogus = array
    ( '@unknown.com'
    , '@example.com'
    , '@gooseball.org'
    )
    ;

    // IF PHP 5.2 OR ABOVE, WE CAN USE THE FILTER
    if (strnatcmp(phpversion(),'5.2') >= 0)
    {
        if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) return FALSE;
    }

    // IF LOWER-LEVEL PHP, WE CAN CONSTRUCT A REGULAR EXPRESSION
    else
    {
        $regex
        = '/'                        // START REGEX DELIMITER
        . '^'                        // START STRING
        . '[A-Z0-9_-]'               // AN EMAIL - SOME CHARACTER(S)
        . '[A-Z0-9._-]*'             // AN EMAIL - SOME CHARACTER(S) PERMITS DOT
        . '@'                        // A SINGLE AT-SIGN
        . '([A-Z0-9][A-Z0-9-]*\.)+'  // A DOMAIN NAME PERMITS DOT, ENDS DOT
        . '[A-Z\.]'                  // A TOP-LEVEL DOMAIN PERMITS DOT
        . '{2,6}'                    // TLD LENGTH >= 2 AND =< 6
        . '$'                        // ENDOF STRING
        . '/'                        // ENDOF REGEX DELIMITER
        . 'i'                        // CASE INSENSITIVE
        ;
        // TEST THE STRING FORMAT
        if (!preg_match($regex, $email)) return FALSE;
    }

    // TEST TO SEE IF THE DOMAIN IS IN OUR BLOCKED LIST
    foreach ($bogus as $badguy)
    {
        if (stripos($email, $badguy)) return FALSE;
    }

    // FILTER_VAR OR PREG_MATCH DOES NOT TEST IF THE DOMAIN IS ROUTABLE
    if ($rout)
    {
        $domain = explode('@', $email);

        // MAN PAGE: http://php.net/manual/en/function.checkdnsrr.php
        if ( checkdnsrr($domain[1], "MX") || checkdnsrr($domain[1], "A") ) return TRUE;

        // EMAIL IS NOT ROUTABLE
        return FALSE;
    }
    return TRUE;
}



// DEMONSTRATE THE FUNCTION IN ACTION
$e = NULL;
if (!empty($_GET["e"]))
{
    $e = $_GET["e"];
    if (check_valid_email($e))
    {
        echo "<br/>VALID: $e \n";
    }
    else
    {
        echo "<br/>BOGUS: $e \n";
    }
}


// END OF PROCESSING - CREATE THE FORM USING HEREDOC NOTATION
$form = <<<ENDFORM
<form>
TEST A STRING FOR A VALID EMAIL ADDRESS:
<input name="e" value="$e" />
<input type="submit" />
</form>
ENDFORM;

echo $form;

Open in new window

And second, will I get a response from the (human) client at the email address.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_3939-Registration-and-Email-Confirmation-in-PHP.html

Apologies -- it's an old article and I have not converted the code samples away from the obsolete MySQL extension.  The MySQL conversion process is described here.
0
 
becraigCommented:
Also please note your script is not failing:
> set q=a
> xxxxxx.com
Server:  ns1.farmtel.net
Address:  167.142.194.178

Non-authoritative answer:
Name:    xxxxxx.com
Address:  176.74.176.179

> yyyyyyy.com
Server:  ns1.farmtel.net
Address:  167.142.194.178

Non-authoritative answer:
Name:    yyyyyyy.com
Address:  62.116.143.21

Those domains are valid registered domains.
0
 
Ray PaseurCommented:
Those domains are valid registered domains.
Yep, cyber-squatted domains.   Click here:  http://yyyyyyy.com/

That's why you really need to execute the handshake in order to know if the email addresses at the domain can get a message to a human being.
0
SMB Security Just Got a Layer Stronger

WatchGuard acquires Percipient Networks to extend protection to the DNS layer, further increasing the value of Total Security Suite.  Learn more about what this means for you and how you can improve your security with WatchGuard today!

 
chanderpal singh rathoreMicrosoft Exchange EngineerCommented:
Hi Ashraf,

You can use this php script for sending mails.


<?php
require_once('class.phpmailer.php');


$mail = new PHPMailer(true);

$mail->IsSMTP(); // telling the class to use SMTP

try {
  $mail->Host       = "mail.physivert.com"; // SMTP server
  $mail->SMTPDebug  = 2;                     // enables SMTP debug information (for testing)
  $mail->SMTPAuth   = true;                  // enable SMTP authentication
  $mail->Host       = "mail.physivert.com"; // sets the SMTP server
  $mail->Port       = 26;                    // set the SMTP port for the GMAIL server
  $mail->Username   = "yourname@yourdomain"; // SMTP account username
  $mail->Password   = "yourpassword";        // SMTP account password
  $mail->AddAddress('whoto@otherdomain.com', 'John Doe');
  $mail->SetFrom('name@yourdomain.com', 'First Last');
  $mail->AddReplyTo('name@yourdomain.com', 'First Last');
  $mail->Subject = 'PHPMailer Test Subject via mail(), advanced';
  $mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
  $mail->MsgHTML("<h1>Haiiiiii</h1>");
  //$mail->AddAttachment('images/phpmailer.gif');      // attachment
  //$mail->AddAttachment('images/phpmailer_mini.gif'); // attachment
  $mail->Send();
  echo "Message Sent OK</p>\n";
} catch (phpmailerException $e) {
  echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
  echo $e->getMessage(); //Boring error messages from anything else!
}


Good Luck, hope this will work.
0
 
Ray PaseurCommented:
@chanderpal: I think the author was looking for a way to see if an email address was valid:
I want to write a script which verifies the email address...
PHPMailer is a useful tool, but it's not really responsive to the question of email verification.
0
 
Ashraf HassaneinAuthor Commented:
@chanderpal thanks for your help but I needed indeed a script to validate the email
@ray, thanks the scripts working pretty fine, but again to the same discussion for all my questions :-) how to integrate this check in my jquery validate, I have found something in this link:
http://www.jquery4u.com/ajax/jquery-ajax-validation-remote-rule/

So I am trying to implement something like it so I changed the php to:
<?php
error_reporting(E_ALL);
// DEMONSTRATE THE FUNCTION IN ACTION
$e = NULL;
if (!empty($_GET["e"]))
{
    $e = $_GET["e"];
    if (check_valid_email($e))
    {
        echo true;
    }
    else
    {
        echo false;
    }
}


// A FUNCTION TO TEST FOR A VALID EMAIL ADDRESS, RETURN TRUE OR FALSE
// SEE MAN PAGE: http://php.net/manual/en/intro.filter.php
function check_valid_email($email, $rout=TRUE)
{
    // LIST OF BLOCKED DOMAINS
    $bogus = array
    ( '@unknown.com'
    , '@example.com'
    , '@gooseball.org'
    )
    ;

    // IF PHP 5.2 OR ABOVE, WE CAN USE THE FILTER
    if (strnatcmp(phpversion(),'5.2') >= 0)
    {
        if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) return FALSE;
    }

    // IF LOWER-LEVEL PHP, WE CAN CONSTRUCT A REGULAR EXPRESSION
    else
    {
        $regex
        = '/'                        // START REGEX DELIMITER
        . '^'                        // START STRING
        . '[A-Z0-9_-]'               // AN EMAIL - SOME CHARACTER(S)
        . '[A-Z0-9._-]*'             // AN EMAIL - SOME CHARACTER(S) PERMITS DOT
        . '@'                        // A SINGLE AT-SIGN
        . '([A-Z0-9][A-Z0-9-]*\.)+'  // A DOMAIN NAME PERMITS DOT, ENDS DOT
        . '[A-Z\.]'                  // A TOP-LEVEL DOMAIN PERMITS DOT
        . '{2,6}'                    // TLD LENGTH >= 2 AND =< 6
        . '$'                        // ENDOF STRING
        . '/'                        // ENDOF REGEX DELIMITER
        . 'i'                        // CASE INSENSITIVE
        ;
        // TEST THE STRING FORMAT
        if (!preg_match($regex, $email)) return FALSE;
    }

    // TEST TO SEE IF THE DOMAIN IS IN OUR BLOCKED LIST
    foreach ($bogus as $badguy)
    {
        if (stripos($email, $badguy)) return FALSE;
    }

    // FILTER_VAR OR PREG_MATCH DOES NOT TEST IF THE DOMAIN IS ROUTABLE
    if ($rout)
    {
        $domain = explode('@', $email);

        // MAN PAGE: http://php.net/manual/en/function.checkdnsrr.php
        if ( checkdnsrr($domain[1], "MX") || checkdnsrr($domain[1], "A") ) return TRUE;

        // EMAIL IS NOT ROUTABLE
        return FALSE;
    }
    return TRUE;
}


?>

 And I have modified the rules section to be something like that:
                var validator = $("#createuser").validate({
                        rules: {
                                username: {
                                        required: true,
                                        minlength: 6,
                                        remote: "useravailable_check.php"
                                },
                                extemail: {
                                        required: true,
                                        email: true,
                                        remote: {
                                           url: "extemail_check.php",
                                           type: "get",
                                           data: { e: function()
                                            {
                                             var extemail =  $('#extemail').val();
                                             extemail =  extemail.replace(/^\s+|\s+$/,'');
                                             return extemail
                                             }
                                           }
                                        }
                                },
                           },
             And the messages to:
                                },
                        messages: {
                              username: {
                                        required: "Enter a username",
                                        minlength: jQuery.format("Enter at least {0} characters"),
                                        remote: jQuery.format("{0} is already in use")
                                },
                                extemail: {
                                        required: "Please enter a valid email address",
                                        minlength: "Please enter a valid email address",
                                        remote: jQuery.validator.format("{0} does not have a valid domain")
                                },
                            },
so it kept complaining about the replace is used with undefined
So I changed it to:
                                           data: { e: function()
                                            {
                                             return $("#extemail").val();
                                             }
                                           }
                                        }
Now it does not complain from the replace but it does not do anthing else :-)
Sorry for keep jumping from one question to anothor but I believe that this problem now is the same as the one I have with mockjax I want just to an remote script for the check.
0
 
Ashraf HassaneinAuthor Commented:
Ok I have found a stupid mistake in the changes I did for the PHP I forgot the quotes in the echo :-)
   so I have changed it to :
       if (check_valid_email($e))
    {
        echo "true" ;
    }
    else
    {
        echo "false" ;
    }


  So it is working now, but with no replace to remove any empty spaces in the value, any clue why?
0
 
Ashraf HassaneinAuthor Commented:
As usual Ray is always great and helpful
0
 
Ray PaseurCommented:
a stupid mistake in the changes I did for the PHP I forgot the quotes
Ha!  I never make that mistake any more because I have already made it about a thousand times :-)

Thanks for the points and thanks for using EE, ~Ray
0
All Courses

From novice to tech pro — start learning today.