Solved

PHP script t verify an email

Posted on 2013-12-23
9
677 Views
Last Modified: 2013-12-26
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.
0
Comment
Question by:Ashraf Hassanein
9 Comments
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
Comment Utility
"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
 
LVL 28

Expert Comment

by:becraig
Comment Utility
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
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
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
 
LVL 5

Expert Comment

by:chanderpal singh rathore
Comment Utility
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
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
@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
 

Author Comment

by:Ashraf Hassanein
Comment Utility
@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
 

Author Comment

by:Ashraf Hassanein
Comment Utility
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
 

Author Closing Comment

by:Ashraf Hassanein
Comment Utility
As usual Ray is always great and helpful
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
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

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Import PST to Exchange using Power Shell new-mailboximportrequest command, you can simply import the PST file into Exchange mailbox or archived. To know How to import PST into Exchange  2013 read the complete article.
Email signatures have numerous marketing benefits. Here are 8 top reasons to turn your email signature into a marketing channel.
In this video we show how to create a Shared Mailbox in Exchange 2013. We show this process by using the Exchange Admin Center. Log into Exchange Admin Center.: First we need to log into the Exchange Admin Center. Navigate to the Recipients >> Sha…
In this video we show how to create a Contact in Exchange 2013. We show this process by using the Exchange Admin Center. Log into Exchange Admin Center.: First we need to log into the Exchange Admin Center. Navigate to the Recipients >> Contact ta…

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now