In the following function, the code first performs basic email validations and then checks whether the domain of each email has a valid MX record. This helps verify if the email address belongs to a real mail server or is likely fake. To perform this verification, we use PHP’s built-in checkdnsrr() function, whose syntax is:
checkdnsrr(string $hostname, string $type = "MX"): bool
This function returns a boolean value:
- The first parameter (
$hostname) is the domain name as a string. - The second parameter (
$type) is optional and specifies the DNS record type to check (default is"MX").
Here’s a working example that filters out invalid or fake email addresses from an array:
<?php
$emails = [
'[email protected]',
'bademail@',
'[email protected]',
'[email protected]'
];
function filter_spam_emails(array $emails): array {
$valid = [];
foreach ($emails as $email) {
$email = trim($email);
// Validate email format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
continue;
}
// Extract the domain from the email
$domain = strtolower(substr(strrchr($email, "@"), 1));
// Check if the domain has an MX record (indicating a real mail server)
if (!checkdnsrr($domain, "MX")) {
continue;
}
$valid[] = $email;
}
return $valid;
}
$clean = filter_spam_emails($emails);
echo "<pre>";
print_r($clean);
Summary:
This script efficiently filters a list of email addresses by validating their syntax and verifying that their domains have MX records. It’s a simple yet effective way to reduce spam or invalid entries when processing user-submitted emails in PHP.