Solved

php email validation for subdomain

Posted on 2013-05-28
15
573 Views
Last Modified: 2013-06-28
1> test@mail.e-treo.biz
2> @mail.e-treo.biz

I want to validate such email ids using regex in php.
username may / may not be present.

currently i am using below regex pattern .
preg_match('/^[a-z0-9\-\_\.]*@[a-z0-9\-]+[\.(a-z)+]+$/', $restContent)

but it fails to validate such emails with subdomains
0
Comment
Question by:Insoftservice
  • 6
  • 5
  • 4
15 Comments
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 39200798
This might help

define('regx_email', '/^[\!-\-\/-\~]*(\.[\!-\-\/-\~]+)*@(([a-z0-9]([-a-z0-9]*[a-z0-9]+)?){1,63}\.)+[a-z0-9]{2,6}$/');

preg_match(regx_email, $restContent);

I modified the below (which requires a name)

define('regx_email', '/^[\!-\-\/-\~]+(\.[\!-\-\/-\~]+)*@(([a-z0-9]([-a-z0-9]*[a-z0-9]+)?){1,63}\.)+[a-z0-9]{2,6}$/');
0
 
LVL 15

Author Comment

by:Insoftservice
ID: 39200814
i have tried this one it worked  but i am not so confident to use it

preg_match('/^[.\w-]*@([\w-]+\.)+[a-zA-Z]{2,6}$/', $restContent)
0
 
LVL 15

Author Comment

by:Insoftservice
ID: 39200839
Tried your code replacing my regex pattern but it failed
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 39200882
failed how?

This worked for me
define('regx_email', '/^[\!-\-\/-\~]+(\.[\!-\-\/-\~]+)*@(([a-z0-9]([-a-z0-9]*[a-z0-9]+)?){1,63}\.)+[a-z0-9]{2,6}$/');

$email = "test@mail.e-treo.biz";

$matches = preg_match(regx_email, $email);
echo "Matches $matches on $email<br/>";

$email = "@mail.e-treo.biz";
$matches = preg_match(regx_email, $email);
echo "Matches $matches on $email<br/>";

Open in new window

Output
Matches 1 on test@mail.e-treo.biz
Matches 1 on @mail.e-treo.biz

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39201181
Here is how I validate an email address.  PHP has a built-in function for this, so you do not need to write your own.  Please treat this as untested code -- I have not tested it with your examples.

<?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

Best to all, ~Ray
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39201286
Now that I have tested it, here are the results.  

The email address $email = 'test@mail.e-treo.biz'; is valid, but the domain name 'mail.e-treo.biz' is not routable per checkdnsrr().  

The email address '@mail.e-treo.biz' is invalid (and this makes sense because it is missing the username before the '@').  

The domain 'e-treo.biz' is unroutable.

If all you want to do is check for a well-formed domain name (which is really all you've got with something like '@mail.e-treo.biz') you might try prepending the letter "X" to the string if the string starts with '@'.   Trim() the string before testing the substr($email,0,1) == '@'.  If needed, add the "X" to the front of the string and then call the built-in PHP validation filter.

Here is the test script.

<?php // RAY_temp_foo.php
error_reporting(E_ALL);
echo '<pre>';


$email = 'test@mail.e-treo.biz';

echo PHP_EOL . "EMAIL: $email";
echo PHP_EOL;
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE)
{
    echo "$email IS BOGUS";
} else echo "Email is OK";
echo PHP_EOL;

$domain = explode('@', $email);

if ( checkdnsrr($domain[1], "MX") || checkdnsrr($domain[1], "A") )
{
    echo "$email IS ROUTABLE";
} else echo $domain[1] . " IS NOT ROUTABLE PER CheckDNSRR()";
echo PHP_EOL;


$email = '@mail.e-treo.biz';

echo PHP_EOL . "EMAIL: $email";
echo PHP_EOL;
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE)
{
    echo "$email IS BOGUS";
} else echo "Email is OK";
echo PHP_EOL;

$domain = explode('@', $email);

if ( checkdnsrr($domain[1], "MX") || checkdnsrr($domain[1], "A") )
{
    echo "$email IS ROUTABLE";
} else echo $domain[1] . " IS NOT ROUTABLE PER CheckDNSRR()";
echo PHP_EOL;


$email = 'test@e-treo.biz';

echo PHP_EOL . "EMAIL: $email";
echo PHP_EOL;
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE)
{
    echo "$email IS BOGUS";
} else echo "Email is OK";
echo PHP_EOL;

$domain = explode('@', $email);

if ( checkdnsrr($domain[1], "MX") || checkdnsrr($domain[1], "A") )
{
    echo "$email IS ROUTABLE";
} else echo $domain[1] . " IS NOT ROUTABLE PER CheckDNSRR()";
echo PHP_EOL;


$email = '@mail.e-treo.biz';

echo PHP_EOL . "EMAIL: $email";
echo PHP_EOL;
if (substr(trim($email), 0, 1) == '@') $email = 'X' . $email;

if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE)
{
    echo "$email IS BOGUS";
} else echo "Email is OK";
echo PHP_EOL;

$domain = explode('@', $email);

if ( checkdnsrr($domain[1], "MX") || checkdnsrr($domain[1], "A") )
{
    echo "$email IS ROUTABLE";
} else echo $domain[1] . " IS NOT ROUTABLE PER CheckDNSRR()";
echo PHP_EOL;

Open in new window

0
 
LVL 15

Author Comment

by:Insoftservice
ID: 39204021
@Ray the domain name is just an example. And its not the actual domain.
I would test both the example provide by you and @ julianH
0
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39204244
the domain name is just an example
Please learn about the SSCCE.  There is no way I could have known your data set provided with the question was hypothetical and bogus, and it look a lot of time to figure out why I kept seeing consistent failures from all the tests.  If you had added a note showing that you expected the validation to fail for the domain name you provided it would have been helpful!

In any case, this question is fully answered with tested and working code samples, so I'll sign off on it now.  Best of luck with your project, ~Ray
0
 
LVL 15

Author Comment

by:Insoftservice
ID: 39214500
@Ray first of all question is not bogus.
I can't provide my clients domain name for testing your php code.
I had requested for validation and not to check whether we could send mails to the concern mails.
pls check my email id. 1> test@mail.e-treo.biz.
Where it specifies its test mail.
actual domain is similar to the mail provided.
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 39215440
@insoftservice - did you see my last post - how did my suggestion fail on your side?
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39215964
pls check my email id. 1> test@mail.e-treo.biz.
I did that already.  I checked all of the test data provided.  I posted the results.  Please see this link:
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28140356.html#a39201286

There was a detailed explanation of what I found, including this:

The email address $email = 'test@mail.e-treo.biz'; is valid, but the domain name 'mail.e-treo.biz' is not routable per checkdnsrr().

0
 
LVL 15

Author Comment

by:Insoftservice
ID: 39218058
hi @julianH i have pasted ur code as below check the o/p


define('regx_email', '/^[\!-\-\/-\~]+(\.[\!-\-\/-\~]+)*@(([a-z0-9]([-a-z0-9]*[a-z0-9]+)?){1,63}\.)+[a-z0-9]{2,6}$/');

$email = "test@mail.e-treo.biz";

$matches = preg_match(regx_email, $email);
echo "Matches $matches on $email<br/>";

$email = "@mail.e-treo.biz";
$matches = preg_match(regx_email, $email);
echo "Matches $matches on $email<br/>";

$email = "@.biz";
$matches = preg_match(regx_email, $email);
echo "match failed $matches on $email<br/>


o/p

Matches 1 on test@mail.e-treo.biz
Matches 0 on @mail.e-treo.biz
match failed 0 on @.biz


I might have done some mistake.
0
 
LVL 51

Accepted Solution

by:
Julian Hansen earned 250 total points
ID: 39218154
Posted wrong expression - change first + to a *

define('regx_email', '/^[\!-\-\/-\~]*(\.[\!-\-\/-\~]+)+@(([a-z0-9]([-a-z0-9]*[a-z0-9]+)?){1,63}\.)+[a-z0-9]{2,6}$/');

Becomes

define('regx_email', '/^[\!-\-\/-\~]*(\.[\!-\-\/-\~]+)*@(([a-z0-9]([-a-z0-9]*[a-z0-9]+)?){1,63}\.)+[a-z0-9]{2,6}$/');
0
 
LVL 15

Author Closing Comment

by:Insoftservice
ID: 39283739
Thanx
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 39283833
You are welcome - thanks for the points.
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Consider the following scenario: You are working on a website and make something great - something that lets the server work with information submitted by your users. This could be anything, from a simple guestbook to a e-Money solution. But what…
These days socially coordinated efforts have turned into a critical requirement for enterprises.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
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 …

744 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

13 Experts available now in Live!

Get 1:1 Help Now