How To Check Email Address Validation In PHP

In this article we will discuss how to check email address validation In PHP. we will verify the email address is in correct format or not.

Example #1 Check Email Address Validation with filter_var() function

In below example we are only checking / validating the format of the email address.


<?php
$email_address_one = 'vikastyagi87@gmail.com';
$email_address_two = 'contactus';

if (filter_var($email_address_one, FILTER_VALIDATE_EMAIL)) {
    echo "Email address '$email_address_one' is correct.<br>";
} else {
    echo "Email address '$email_address_one' is not correct.<br>";
}

if (filter_var($email_address_two, FILTER_VALIDATE_EMAIL)) {
    echo "Email address '$email_address_two' is correct.<br>";
} else {
    echo "Email address '$email_address_two' is not correct.<br>";
}
?>

The above example will output:

Email address 'vikastyagi87@gmail.com' is correct.
Email address 'contactus' is not correct.

Example #2 Check Email Address Validation with filter_var() function and checking the validation or existence of the URL

In this function we are checking / validating the format of the email address, it also checking the validation or existence of the URL or the service provider.

<?php
$email="test@gmail.com";
if (isValidEmail($email))
{
  echo "Correct email address.";
}
else
{
   echo "Sorry! wrong email address.";
}

//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;
}
?>

The above example will output:

Email address 'vikastyagi87@gmail.com' is correct.
Email address 'contactus@thecodedevelopers.com' is not correct.

Leave A Reply

Your email address will not be published.