Validating Email Addresses

How to check whether a string contains a valid email address or not.

Email addresses are another common data entry item that requires field organization checking. There is a standard maintained by the Internet Engineering Task Force (IETF) that defines what a valid email address can be, and it’s much more complex than might be expected.

We use the filter_var() function and checkdnsrr() function to validate an email address:

 $email = '';

 if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  die ('An invalid email format found.');

 $host = substr(strstr($email, '@'), 1);
 $ip = gethostbyname($host);

 if ($ip == $host) {
  die ('The domain does not exist.');
 if (!checkdnsrr($host, 'MX')) {
  die ('MX records not found for this domain.');
 echo "$email is a valid email address.";

The first check tests to ensure an email address has been entered in a valid format. If not, an error is generated. The function checkdnsrr() queries an Internet domain name server (DNS) to check if there is a record of the email domain as a mail exchanger (MX). If the MX record is not found, the domain of the email address isn’t valid and we reject the email address.