Wordpress Plugins

PHP Scripts

Tutorial: How to validate an email address in PHP

PHP (>= 5.2.0) has an build in function to validate an email address: filter_var.

Example:

if ($isemail=filter_var('bob@example.com', FILTER_VALIDATE_EMAIL))
{ echo "$isemail is a valid email address"; } else
{ echo "$isemail is no valid email address"; }
The problem with the code above is that it doesn't check if the given domain is a valid domain name. If you will check for example aaaa@1111.xyz with the standard PHP function it will return TRUE.

In the following example I will show you a function which checks for a valid email based on the email address and the domain name. $emailtocheck="bob@example.com";

if (isvalidemail($emailtocheck))
{ echo "$emailtocheck is a valid email address"; } else
{ echo "$emailtocheck is no valid email address"; }

function isvalidemail ($email) {
if ($isemail=filter_var($email, FILTER_VALIDATE_EMAIL))
{
list($email,$domain)=split('@',$email);

if(!getmxrr ($domain,$mxhosts)) { return FALSE; }
else { return TRUE; }
}

else
{
return FALSE;
}

}

In the example above first of all the email address will be checked with the standard PHP function. If it passes the check a second check will be done if the domain name exists. In our example bob@example.com will return FALSE since example.com isn't a valid domain.

However the function is good to use on checking the validity of an email address, it doesn't say anything about if the mailbox exists.