Reading Malcolm McDonald's Web Security for Developers: Real Threats, Practical Defense for a class I am instructing, he mentioned this Python tidbit that can check if a given domain is likely setup to handle email:
import dns.resolver
def email_domain_is_valid(domain):
for _ in dns.resolver.query(domain, 'MX'):
return True
return False
I asked ChatGPT for the PHP equivalent:
function emailDomainIsValid($domain) {
return checkdnsrr($domain, "MX");
}
and then a version where I can just pass in the full address, and it will get a clean version of the email address, or else return false:
function cleanEmailWithValidDomain($email) {
// Trim whitespace from the email
$email = trim($email);
// Validate the email address
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
return false;
}
// Extract the domain from the email address
$domain = substr(strrchr($email, "@"), 1);
// Check for MX records
if (checkdnsrr($domain, "MX")) {
return $email;
}
return false;
}
Somehow I missed that you could do that kind of serverside check; I think I read "you can't really tell if an email is legit" too much to heart.
No comments:
Post a Comment