Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

PHP script t verify an email

Posted on 2013-12-23
9
Medium Priority
?
704 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
9 Comments
 
LVL 111

Accepted Solution

by:
Ray Paseur earned 2000 total points
ID: 39737137
"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 29

Expert Comment

by:becraig
ID: 39737141
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 111

Expert Comment

by:Ray Paseur
ID: 39737155
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
Get free NFR key for Veeam Availability Suite 9.5

Veeam is happy to provide a free NFR license (1 year, 2 sockets) to all certified IT Pros. The license allows for the non-production use of Veeam Availability Suite v9.5 in your home lab, without any feature limitations. It works for both VMware and Hyper-V environments

 
LVL 5

Expert Comment

by:chanderpal singh rathore
ID: 39737956
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
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 39738018
@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
ID: 39738726
@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
ID: 39738735
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
ID: 39739953
As usual Ray is always great and helpful
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 39739969
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

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

There are times when I have encountered the need to decompress a response from a PHP request. This is how it's done, but you must have control of the request and you can set the Accept-Encoding header.
This article outlines some of the reasons why an email message gets flagged as spam on a recipient's end.
In this video we show how to create a mailbox database 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 Servers >> Data…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

670 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