Please Like our Facebook Page

How to validate email address using PHP


How to validate email address using PHP. Sometimes you might require a simple and straightforward way of form validation using PHP without the need to employ javascript. Today we are going to learn how to validate email address using PHP.

How to Validate Email Address using PHP

There are several methods which can be used to validate an email address in PHP:

  1. Manual method
  2. Using PHP inbuilt email validater

Make sure you also read: PHP tutorial, How to detect links in the comments



1. Manual Method
To some extent, this would be the best method for me, as it can give you more control, for example, let’s say your company accepts only Gmail emails, using this method, you can manually filter non-Gmail emails efficiently. This method will require us to use PHP inbuilt function strpos(haystack, needle), where heystack will be our email and needle will be filtering character. This method requires you to understand your string, for example, we all know a valid email adress must contain @ and dot (.). Kindly have a look at the code below

Make sure you also read: How to check if php strings contains other strings or specific word

$email = $_POST['email']; // get email from a form

if(strpos($email, '@') === false || strpos($email, '.' === false)){
	// invalid email
} else {
	// valid email address
}

strpos($email, ‘character’), returns true if condition inside the function is met or false if condition inside the function is not met

2. Using PHP inbuilt email validater
You can validate email address in php using PHP FILTER_VALIDATE_EMAIL Filter as shown in the code below

Make sure you also read: How to use SQL LIKE Clause in A PDO Prepared Statement

<?php
$email = "john.doe@example.com";

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
  echo("$email is a valid email address");
} else {
  echo("$email is not a valid email address");
}
?>


filter_var is PHP’s inbuilt function and FILTER_VALIDATE_EMAIL is PHP inbuilt constant.

In case you get any question or difficulties while executing this code, kindly leave a short message in the commenting system below and I will reply as soon as possible










Please Like us on Facebook