Email validity at domain level in a WordPress comment


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 somone@somewhere.travel at the blog post at http://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.
Subscribe to my newsletter
Read articles from Anjanesh Lekshminarayanan directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Anjanesh Lekshminarayanan
Anjanesh Lekshminarayanan
I am a web developer from Navi Mumbai. Mainly dealt with LAMP stack, now into Django and getting into Laravel and Google Cloud. TensorFlow in the near future. Founder of nerul.in and gaali.in