2

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.

0

2 Answers 2

5

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.

2
  • 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? Commented Feb 27, 2013 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. Commented Feb 27, 2013 at 12:48
2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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