Email validation in PHP using FILTER_VALIDATE_EMAIL

Validating email on the server side is a secure way than validating it on the client side. If the email is validated just by using JavaScript then remember, JavaScript easily can be disabled and also keeping the input field name as email can be changed easily.

So in this post, we are going to see how to validate email in PHP. Here we are going to use PHP filter_var() function and the FILTER_VALIDATE_EMAIL filter that validates an e-mail address.

Generate PDF from HTML template in PHP using Dompdf

How to unzip or extract zip files in PHP?

Below is the given PHP code that first checks if the variable passing through is a valid email or not and depending upon that it will returns message:

<?php
$email = "[email protected]";

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

On the above code, we have first take the email address in a variable $email and after that, we have used FILTER_VALIDATE_EMAIL filter with filter_var PHP function to check if the email is valid or not. Here we have used if else statement to express the condition. Depending on the validity of the email it will display the different message.

The below code is another example of validation an email but with the slightly different technique:



<?php
$email = "[email protected]";

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

In the above code, the output will be same as previous one. But the difference is that previously we first check if the email is valid and now we are checking if the email is not a valid email. We have just change the position of messages and the same output will be generated from both of these two examples.

How to send email using PHP mail() function?

What is a function in PHP and why we use it?

Of course, the process of checking email if it is valid or not is so simple and it can be done with just a few lines of code. Thus FILTER_VALIDATE_EMAIL filter is so helpful and simplifies our work in validating email. You don’t need to use preg_match function to defined all the characters, symbols etc which is much more complicated.

So be happy in using FILTER_VALIDATE_EMAIL filter to validate email.

Leave a Reply

Your email address will not be published. Required fields are marked *