Article content

How to verify a user's email address using PHP

Tagged in php, validate, email, tutorial

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)

Discussion
25.08.2009 04:27
Perfect. Though, I don't have 5.2, so I stripped that part, and it still works fine :)jacob

Submit your comment

Text:

Your name:

Your email:

Show my mailaddress (spam protected)

Your website:

Show my website

Featured Article

PHP Variables and strings

A variable is a means of storing a value, such as a text string or a number. In PHP you do not have to declare your variable, as it's automatically declared when you set it. Since you do not need to declare the variable, you do not have to specify what kind of data it contains either.

Topics
Magicode's own open source project
From the forum / Latest comments
You may also want to to check out these links: sendanonmail.com, superstrongpassword.com.