Email Validation in PHP

Email validation in PHP is the process of verifying whether the submitted email address from an HTML form is valid and properly formatted. This validation checks the following:

  • Whether the format is proper (e.g., example@domain.com).
  • That it does not contain illegal characters.
  • Whether it follows the standard email structure (username@domain).

Why Validate Email?


Validating an email address in PHP is an essential step for the reliability, security, and quality of your web application. Here’s why:

(1) Prevent Invalid Data: When users submit incorrect or poorly formatted email addresses (such as missing @ symbol or domain name), your database can become filled with invalid data. Email validation ensures that only properly formatted email addresses are accepted, helping to maintain a clean and usable database.

(2) Ensure Successful Email Communication: If a user enters an invalid email address, he won’t receive important emails, such as account activation, password resets, or newsletters. Validating email addresses ensures you can successfully communicate with your users without email delivery failures.

(3) Block Spam Bots:

Spam bots often submit fake or malicious email addresses through HTML forms. By validating email inputs, you can block such fake or spam email submissions generated by bots and protect your application.

(4) Improve Data Integrity: Clean, valid, and verified email addresses improve the overall data integrity of your application. This is especially important for analytics, marketing campaigns, or CRM systems, where accurate user data is crucial.

Methods to Validate Email in PHP


PHP offers multiple ways to validate email addresses. The most common ones include:

  • filter_var() with FILTER_VALIDATE_EMAIL (Recommended)
  • Regular Expressions (Regex)
  • Custom Validation Functions

Let’s explore each one with examples.

Email Validation in PHP Using filter_var() Function


The filter_var() function is the simplest and most reliable way to validate an email address in PHP. This is a built-in function in PHP which is used to filter and validate input data. The filter_var() function is included with PHP version 5.2 and later. The general syntax of this function is as:

filter_var(value, FILTER_VALIDATE_EMAIL);

In the above syntax, the function takes two parameters:

  • value: This parameter represents the email address you want to validate.
  • FILTER_VALIDATE_EMAIL: This is a predefined filter in PHP that you want to validate an email address.

The function filter_var() is used in conjunction with FILTER_VALIDATE_EMAIL to check whether the email that was entered is a valid or not according to the standard email format.

Example 1: Email Validation using HTML Form and PHP

This example demonstrates how to validate an email address submitted via an HTML form using built-in filter_var() function provided by PHP. Follow the below steps.

Step 1: Create an HTML form and save it form.html.

<!DOCTYPE html>
<html>
<head>
    <title>Email Validation</title>
</head>
<body>
    <form method="POST" action="validate.php">
      <label for="email">Enter your email:</label>
      <input type="text" name="email" id="email" required>
      <input type="submit" value="Validate">
    </form>
</body>
</html>

Step 2: Create a PHP script to process HTML form and save it with validate.php.

<?php
// Check if the form was submitted using the POST method.
if ($_SERVER["REQUEST_METHOD"] == "POST") {

// Get the email input submitted from the HTML form and remove extra whitespace.
   $email = trim($_POST["email"]);

// Validate the email format using filter_var() function.
   $email_filter = filter_var($email, FILTER_VALIDATE_EMAIL);

// Check if the email is valid or not.
   if ($email_filter) {
       echo "Valid email address.";
   } else {
       echo "Invalid email address.";
   }
} else {
// If the form was not submitted, display a message.
   echo "Please submit the form.";
 }
?>
Output:
      Valid input: user@example.com
      Valid email address.
      Invalid input: user@@example..com
      Invalid email address.

Email Validation Using Regular Expressions


Sometimes you may need more control over the format. You can use regular expressions (regex) to validate the format of email address more strictly.

Regular expressions provide a powerful way to define patterns for matching text. In email validation, regex checks that the input string matches the standard structure of an email address. Let’s write PHP script to validate the format of email address using regex.

Example 2: Email Validation using Regex

Step 2: PHP script (validate.php)

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the email input submitted from the HTML form.
// The trim() function removes spaces from beginning and end of the email address.
   $email = trim($_POST["email"]);

// Define regex pattern for validating email address.
   $pattern = "/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-z]{2,}$/";

// Display the entered email address.
   echo "<h3>Entered Email: $email</h3>";

// Perform email validation using preg_match() function.
   if (preg_match($pattern, $email)) {
       echo "Valid email address.";
   } else {
       echo "Invalid email address.";
   }
   } else {
       echo "Please submit the form.";
}
?>
Output:
       Valid input: example.user@gmail.com
       Entered Email: example.user@gmail.com
       Valid email address.
     
       Invalid input: user@@gmail
       Entered Email: user@@gmail
       Invalid email address.

Custom Email Validation Function


You can also create a custom function to validate the format of an email address. You can check the basic format using the filter_var() function and add extra conditions like domain verification, blocking specific domains, or applying custom email rules.

Step 2: PHP script with custom function (validate.php)

<?php
// Create a custom function to validate email address.
function validateEmail($email) {
// Trim and sanitize email.
   $email = filter_var(trim($email), FILTER_SANITIZE_EMAIL);

// Check the format of email using filter_var() function.
   if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
       return "Invalid email format.";
   }

// Extract domain from email.
   $domain = substr(strrchr($email, "@"), 1);

// Check if the domain has MX records.
   if (!checkdnsrr($domain, "MX")) {
      return "Email domain does not exist.";
   }

// Optional: Block specific domains.
   $blocked_domains = ["tempmail.com", "mailinator.com"];
   if (in_array($domain, $blocked_domains)) {
      return "Disposable email addresses are not allowed.";
   }

   return "Valid email address.";
}

if($_SERVER["REQUEST_METHOD"] == "POST") {
    $email = $_POST["email"];
    echo "<h3>Entered Email: $email</h3>";
    echo "<p>" . validateEmail($email) . "</p>";
} else {
    echo "Please submit the form.";
}
?>
Output:
      Valid input: user@gmail.com
      Entered Email: user@gmail.com
      Valid email address.
      Input: someone@fakedomain123.com (non-existent domain)
      Entered Email: someone@fakedomain123.com
      Email domain does not exist.

In this tutorial, you learned about email validation in PHP with the help of various examples. Email validation is essential for developing secure, professional, and user-friendly web applications. Whether you are building a contact form, signup page, or email marketing tool, validating email addresses using filter_var() is your best choice.