Validate email domain using PHP’s checkdnsrr with CodeIgniter

I recently noticed a bunch of garbage registrations for an existing client’s newsletter function written quite some time ago. After making a copy of the subscribers table and “cleaning” the data (proper-cased names, lowercased emails, etc), I started looking at ways to limit these automated registrations.

The client would not be happy with registration confirmation emails, so I decided to make a callback function for use with CodeIgniter’s Form Validation library. Since it was only needed in one location, this method made more sense to me than extending the main library.

Here is the function…

function _valid_domain($str)
{
 list($mailbox, $domain) = split('@', $str);
 if (!(checkdnsrr($domain, 'MX') || checkdnsrr($domain, 'A'))) {
  $this->form_validation->set_message(__FUNCTION__, "Domain "{$domain}" not found.");
  return FALSE;
 }
 return TRUE;
}

And how to use it…

$this->form_validation->set_rules('email', 'Email Address', 'required|valid_email|strtolower|callback__valid_domain');

You will notice that I am also doing other checks and conversions. If I understand the form validation library correctly, rules are processed in the order provided. So if everything else checks out, the last thing I do is validate the domain protion of the email address.

Note: _valid_domain depends on checkdnsrr(). This function was added to Linux in PHP 4, but did not get implemented on Windows until PHP 5.3.0. Review PHP’s checkdnsrr() documentation for more information.

One thought on “Validate email domain using PHP’s checkdnsrr with CodeIgniter

  1. Sagar

    Hi,
    I want to check the email address only example@examle.edu do you know how to write a call back function for this.I want only the .edu to check please help if you know.

    Thanks and Regards,
    Sagar Sreejith.

    Reply

Leave a Reply to Sagar Cancel reply

Your email address will not be published. Required fields are marked *