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:
- Will it flag a valid emails as a false positive?
- Is it okay to depend on a DNS check to validate the domain?
Any help is appreciated. Thanks.
0
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
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.