How to verify a user's email address using PHP
We've all experienced it. You've made a registration form hoping to gather a collection of email addresses, and all you're getting are addresses like "aKijMH@clqLQf.com" or "PxElDI@IUXadt.com". Not only are they cluttering up your database, you're also going to be sending your emails to a bunch of nonexistent addresses. Here's how to avoid this by verifying and validating a user's email address using PHP.
First of all we're going to use a simple built-in verifier that comes with PHP, called FILTER_VALIDATE_EMAIL.
if (!filter_var($input, FILTER_VALIDATE_EMAIL)) {
// Do nothing
}
Permalink for this article http://mirror.magicode.org/content/9201_how_to_validate_and_verify_email_addresses_with_PHP
This code will stop any attemps to register a emailadress that doesn't validate (for instance a random string of letters without the at-sign (@)). However, this alone is not enough, but it's fine for setting up our next check, where we'll use PHP's checkdnsrr function to see if we can reach the host. Notice! The function filter_var requires PHP 5.2 or above. This text was originally written for http://blog.magicode.org
if(strpos($input,"@")) list($userName, $mailDomain)
= split("@", $input);
if ($mailDomain!="" && (checkdnsrr($mailDomain, "MX")||
checkdnsrr($mailDomain, "A"))) {
//Email is OK!
}
If you see this notice on any site other than magicode.org, it's probably been lifted without consent
This code takes the input and strips out the username from the domain, and then checks to see if the domain is real. If it is, then it produces a true condition.
Final code:
if (filter_var($input, FILTER_VALIDATE_EMAIL)) {
if(strpos($input,"@")) list($userName, $mailDomain)
= split("@", $input);
if ($mailDomain!="" && (checkdnsrr($mailDomain, "MX")||
checkdnsrr($mailDomain, "A"))) {
//Email is OK!
}
}
Conclusion
While there's no foolproof way of stopping your users from typing in fake addresses, the described method will at least make sure they are typing in an address that correspond to a working domain.
You can download the code here:
validateEmail.zip (1.12Kb)
