Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I wrote the following function to validate emails for a web app I'm working on:

function validate_email($email) {
    $valid = true;

    if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $valid = false;
    }

    $email_parts = explode("@", $email);

    if(count($email_parts) < 2) {
        $valid = false;
    }
    else {
        if(!checkdnsrr($email_parts[1], "MX")) {
            $valid = false;
        }
    }

    return $valid;
}

It's not intended to replace the validation email sent to the user with a link to complete the registration. I know it wont catch all invalid ones, it will just reduce them. Hence reduce the amount of bounced emails received. My questions are:

  1. Will it flag a valid emails as a false positive?
  2. Is it okay to depend on a DNS check to validate the domain?

Any help is appreciated. Thanks.

share|improve this question
add comment

2 Answers

up vote 5 down vote accepted

Yes, it will flag valid e-mails incorrectly. An e-mail address can legally contain an escaped @ in the local part, in which case your code would fail to correctly extract the domain name.

Rather than re-invent the wheel, check out IsEmail.

share|improve this answer
    
Maybe its a bad idea, I just need to see it through. So if I changed the code to use the last array element instead of the second one, to make sure it always checks the domain name and not part of the name, will that work? –  Amgad Suliman Feb 27 '13 at 12:09
    
@AmgadSuliman, probably not, but if you download IsEmail you can use its test suite to check most if not all of the corner cases. –  Peter Taylor Feb 27 '13 at 12:48
add comment

That MX DNS record is needed to send any email to the domain. So the check will only flag emails to which it is not possible to deliver email at this time.

The mail transfer agent (MTA) will normally try again, though. It usually retries for about a week. So MTA would deliver the email if there was either temporary misconfiguration of the domain or temporary problem with your local DNS that will cause the check to fail where it would succeed at another time.

Such case would be very rare and if the user expects to be sent confirmation email immediately, they wouldn't be getting it anyway.

See also Peter Taylor's answer for bug in the parsing itself.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.