Email validity at domain level in a WordPress comment

Email validity at domain level in a WordPress comment

Check for an invalid email address by checking availability of MX records before a comment is posted on a WordPress post

I am using MAMP PRO on a macOS Mojave 10.14.6

Let's assume you have installed WordPress 6.1.1 or newer having PHP 8.x at a location named /wordpress

Type this in the terminal at /wordpress: - we're installing composer.

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('sha384', 'composer-setup.php') === '55ce33d7678c5a611085589f1f3ddf8b3c52d662cd01d4ba75c0ee0459970c2200a51f492d557530c71c15d8dba01eae') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php
php -r "unlink('composer-setup.php');"

Now we need to install a PHP library from the composer repository called Spatie DNS.

php composer.phar require spatie/dns

In case there isn't a functions.php in your theme like in the latest twentytwentythree theme, then create one at /wordpress/wp-content/themes/twentytwentythree

Type this in functions.php :

require_once 'vendor/autoload.php';
use Spatie\Dns\Dns;

function comment_post_check_MX() 
{
    $domain = substr(strstr($_POST['email'], '@'), 1);

    $dns = new Dns();
    $dns->useNameserver('8.8.8.8'); // We're using Google's name servers
    $records = $dns->getRecords($domain, DNS_MX);    

    if (count($records) > 0)
    {
        $MXOfFirstRecord = $records[0]->target();
        if ($MXOfFirstRecord == '')
        {            
            wp_die( __('Error: The mail record for this domain seems to be empty') );
        }
    }
    else
    {        
        wp_die( __("Error: There doesn't seem to be any mail records for this domain") );
    }    
}

add_action('pre_comment_on_post', 'comment_post_check_MX', 10);

Now, if you type in an invalid email address like at the blog post at wordpress/2023/01/21/hello-world (or at your local domain like wordpress.local), your WordPress should return an error message like this one below before even the comment is posted/saved to the database.