#native_company# #native_desc#
#native_cta#

E-mail Validation–Check format and MX records

By Laurence O’Donnell
on June 29, 2001

Version: 1.0

Type: Sample Code (HOWTO)

Category: Other

License: GNU General Public License

Description: Get rid of fake e-mail addresses from your user inputs.

This script not only checks the validity of the format of the e-mail address, but it attempts to connect to the mail server of the submitted e-mail address as well. Don’t settle for a database full of fake e-mail addresses.

// Set the form error check to false
$form_errors = array();

//E-Mail address verifications
  // Make Email a required field
  $Email = trim($Email);
    if ($Email == "") {
      $form_errors["required_Email"] = true;
    }
    elseif (!eregi("^([a-zA-Z0-9._-])+@([a-zA-Z0-9._-])+.([a-zA-Z0-9._-])([a-zA-Z0-9._-])+", $Email)) {
      $form_errors["Email_badformat"] = true;
    }
    // Attempt to resolve the MX host
    else {
      list($user, $domain) = split("@", $Email, 2);
      if (! checkdnsrr($domain, "MX")) {
        $form_errors["Email_badhost"] = true;
      }
    }

// Check if there are any errors
if (count($form_errors)) {
  // If the user left the e-mail field blank
  if ($form_errors["required_Email"]) {
    echo("<font color="#ff0000"><b>Your E-mail Address is required.</b></font>");
  }
  // If the format of the e-mail address is incorrect
  elseif ($form_errors["Email_badformat"]) {
    echo("<font color="#ff0000"><b>Please enter a valid e-mail address.</b></font>");
  }
  // If the mail server of the address the user provided could not be contacted
  elseif ($form_errors["Email_badhost"]) {
    echo("<font color="#ff0000"><b>Your E-mail address did not resolve to a working e-mail server.<br> Please enter a valid e-mail address.</b></font>");
  }
}