Thursday, February 22, 2018 04:08 am EST

PHP Email Address Validation

Bri's picture

Email address validation is a very common thing and it's pretty easy in php 5.2 or greater. You no longer need to use a regular expression. You can use this simple script below, making use of the filter_var function.


$email = 'mail@example.com';
$validation = filter_var($email, FILTER_VALIDATE_EMAIL);

if($validation)
$output = 'proper email address';
else
$output = 'wrong email address';

echo $output;

The filter_var function will return the filtered data if it passes, or False if it doesn't pass. If you want something even more advanced, try the following:


<?php
$email="test@geemail.com";
if (isValidEmail($email))
{
echo "Hooray! Adress is correct.";
}
else
{
echo "Sorry! No way.";
}

//Check-Function
function isValidEmail($email)
{
//Perform a basic syntax-Check
//If this check fails, there's no need to continue
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
return false;
}

//extract host
list($user, $host) = explode("@", $email);
//check, if host is accessible
if (!checkdnsrr($host, "MX") && !checkdnsrr($host, "A"))
{
return false;
}

return true;
}
?>

This one not only checks if the format of the email address is correct, it also performs a test to see if the host exists.