Verify a User’s Email Address Using PHP

Share this article

We’ve all seen it happen.

You put up a registration page on your site, hoping that visitors will leave you their email addresses so that you can stay in touch with them when you’ve got a new product for sale. Or a new tutorial that they might be interested in. Or you want to send them some “information from carefully screened third parties with whom we maintain a strategic relationship.” Or maybe you want something in return before you give them that valuable whitepaper that you spent two months completing.

Whatever the reason, you happily construct your registration page, set up a database table to track the incoming email addresses, and publish it live. And sure enough, the registrations start coming in.

To mickey@mouse.com. And donald@duck.com. And emailthis@hahaha.com. You get the idea — users are registering with bogus email addresses at domains that don’t even exist. Not only are you going to be sending mail to nonexistent addresses, but they clutter up your database and cause maintenance headaches because they need to be cleaned out.

Make Sure They’re at Least Real

One way to help address this problem is to make sure that a user’s email address actually corresponds to a real email domain. Using PHP, you can check the domain registration records to see if the domain a user submitted to your site is real. To do this, we’ll use PHP’s checkdnsrr function.

The checkdnsrr function looks up the dns record for a given type, and a given host. It has this format:

int checkdnsrr(string host [,string type]);

This PHP function checks the DNS records for the given host to see if there are any records of the specified type. Note that the type parameter is optional, and if you don’t supply it then the type defaults to “MX” (which means Mail Exchange). If any records are found, the function returns TRUE. Otherwise, it returns FALSE.

To use this function, you submit a potential email address to it and check the result, as shown below:

// take a given email address and split it into the  
username and domain.
list($userName, $mailDomain) = split("@", $email);
if (checkdnsrr($mailDomain, "MX")) {
 // this is a valid email domain!
}
else {
 // this email domain doesn't exist! bad dog! no biscuit!
}

The code above takes a string of the form “username@emaildomain.com” and checks to see if the domain is real. First, the code calls the split() function to split the email string into “username” and “emaildomain.com”, as we’re only interested in the domain.

Once we’ve got the domain, the code calls checkdnsrr, with the domain string and “MX” as the arguments. The second argument tells checkdnsrr what type of DNS record to look for. As we’re interested only in whether the given domain can handle email, we use the “MX” argument, which means “look for the Mail Exchange record.”

If the checkdnsrr function returns TRUE, then we know we’ve got a valid email domain (but not necessarily a valid user name). If the function returns FALSE, then the email domain given is invalid.

Gotcha! – checkdnsrr Doesn’t Do Windows (Yet)

There’s one small problem, however, if you’re using PHP on a Windows server. The checkdnsrr function is not implemented on the Windows platform, so if you’re going to deploy this code on a Windows-based machine, you’ll need to do some extra work yourself.

The way to get around this problem is to write your own version of checkdnsrr. We’ll call our version myCheckDNSRR, the code for which is as follows:

function myCheckDNSRR($hostName, $recType = '') 
{
 if(!empty($hostName)) {
   if( $recType == '' ) $recType = "MX";
   exec("nslookup -type=$recType $hostName", $result);
   // check each line to find the one that starts with the host
   // name. If it exists then the function succeeded.
   foreach ($result as $line) {
     if(eregi("^$hostName",$line)) {
       return true;
     }
   }
   // otherwise there was no mail handler for the domain
   return false;
 }
 return false;
}

Our version of the checkdnsrr function works by taking advantage of a system call that’s available in Windows called nslookup, which performs essentially the same function. To call the nslookup function, our code uses PHP’s exec function, which executes a system command. It returns the result of the command as an array of strings in the $result parameter.

When the nslookup function successfully finds an entry for the given domain, the output will look something like this:

Server: o1-sjc-ns1.o1.com 
Address: 66.81.7.158
joemarini.com MX preference = 0, mail exchanger = smtp.joemarini.com

To determine whether a mail handler for the domain exists, the function loops through each line of the output in search of the line that starts with the given host name. If such a line is found, then the function returns TRUE, otherwise it returns FALSE.

Conclusion

While there’s no foolproof way to make sure a user isn’t giving you a completely bogus email address, you can at least help cut down on the problem by making sure that email addresses your site is given at least correspond to a real domain. Using PHP’s checkdnsrr function, you can look up the registration record for a given domain and see if it’s a real domain before saving away a user’s email address.

Download the code for this article.

Frequently Asked Questions (FAQs) about Using PHP to Validate User’s Email Address

How can I validate an email address using PHP without using regular expressions?

PHP provides a built-in function called filter_var() that can be used to validate an email address without the need for regular expressions. This function filters a variable with a specified filter. To validate an email, you can use the FILTER_VALIDATE_EMAIL filter. Here’s an example:

$email = "test@example.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo("Email is valid");
} else {
echo("Email is not valid");
}
This code will output “Email is valid” if the email address is valid, and “Email is not valid” otherwise.

What are the limitations of using filter_var() for email validation in PHP?

While filter_var() with FILTER_VALIDATE_EMAIL is a quick and easy way to validate an email address in PHP, it has some limitations. It only checks if the email address is in a valid format, but it doesn’t check if the email address actually exists or if it’s deliverable. To check if an email address is deliverable, you would need to use an SMTP server and the checkdnsrr() function in PHP.

How can I use regular expressions to validate an email address in PHP?

Regular expressions provide a more flexible way to validate email addresses in PHP. Here’s an example of how you can use a regular expression to validate an email address:

$email = "test@example.com";
$pattern = "/^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/";
if (preg_match($pattern, $email)) {
echo("Email is valid");
} else {
echo("Email is not valid");
}
This code will output “Email is valid” if the email address is valid, and “Email is not valid” otherwise.

How can I check if an email address is deliverable in PHP?

To check if an email address is deliverable, you can use the checkdnsrr() function in PHP. This function checks the DNS records for a domain. Here’s an example:

$email = "test@example.com";
$domain = substr($email, strpos($email, '@') + 1);
if (checkdnsrr($domain, 'MX')) {
echo("Email is deliverable");
} else {
echo("Email is not deliverable");
}
This code will output “Email is deliverable” if the email address is deliverable, and “Email is not deliverable” otherwise.

How can I sanitize an email address in PHP?

PHP provides a built-in function called filter_var() that can be used to sanitize an email address. To sanitize an email, you can use the FILTER_SANITIZE_EMAIL filter. Here’s an example:

$email = "test@example.com";
$sanitized_email = filter_var($email, FILTER_SANITIZE_EMAIL);
echo($sanitized_email);
This code will output the sanitized email address.

How can I validate multiple email addresses in PHP?

To validate multiple email addresses in PHP, you can use a loop and the filter_var() function. Here’s an example:

$emails = ["test@example.com", "invalid email"];
foreach ($emails as $email) {
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo("Email is valid");
} else {
echo("Email is not valid");
}
}
This code will output “Email is valid” for each valid email address, and “Email is not valid” for each invalid email address.

How can I handle errors when validating an email address in PHP?

To handle errors when validating an email address in PHP, you can use try-catch blocks. Here’s an example:

$email = "test@example.com";
try {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new Exception("Email is not valid");
}
echo("Email is valid");
} catch (Exception $e) {
echo($e->getMessage());
}
This code will output “Email is valid” if the email address is valid, and “Email is not valid” if the email address is not valid.

How can I validate an email address in PHP using HTML5?

HTML5 provides a built-in way to validate an email address using the “email” input type. Here’s an example:

<form action="submit.php" method="post">
<input type="email" name="email" required>
<input type="submit" value="Submit">
</form>
This code will automatically validate the email address and display an error message if the email address is not valid.

How can I validate an email address in PHP using AJAX?

To validate an email address in PHP using AJAX, you can send a request to a PHP script that validates the email address and returns the result. Here’s an example:

$.ajax({
url: 'validate_email.php',
type: 'post',
data: {email: 'test@example.com'},
success: function(response) {
if (response == 'valid') {
alert('Email is valid');
} else {
alert('Email is not valid');
}
}
});
In the validate_email.php script, you can use the filter_var() function to validate the email address.

How can I validate an email address in PHP using a third-party library?

There are many third-party libraries available that can be used to validate an email address in PHP. One popular library is PHPMailer. Here’s an example of how you can use PHPMailer to validate an email address:

require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->setFrom('test@example.com');
if (!$mail->validateAddress('test@example.com')) {
echo("Email is not valid");
} else {
echo("Email is valid");
}
This code will output “Email is valid” if the email address is valid, and “Email is not valid” if the email address is not valid.

Joe MariniJoe Marini
View Author

Joe was an original member of the Dreamweaver development team at Macromedia, and has authored several books on web development. Today he is a senior engineer at Panscopic Corporation. Visit him at www.joemarini.com.

Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form