How to validate an email address using PHP?

Learn various methods to validate whether a given email address is correct or not.
Submitted by Sayesha Singh, on June 18, 2020 [Last updated : March 14, 2023]

PHP - Validating Email Address

Suppose there is a form floating where every user has to fill his/her email ID. It might happen that due to typing error or any other problem user doesn't fill his/her mail ID correctly. Then at that point, the program should be such that it should print a user-friendly message notifying the user that address filled is wrong. This is a simple program and can be done in two ways in PHP language.

Naive approach

There is a filter called FILTER_VALIDATE_EMAIL which is in-built in PHP and validates mail ID.

The function filter_var() is also used in this program which takes two arguments. The first is the user mail ID and the second is the email filter. The function will return a Boolean answer according to which we can print the message of our desire.

Example 1: PHP code to validate an email address

<?php

    $email = "[email protected]";
    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
         echo '"' . $email . ' " is valid'."\n";
    }
    else {
         echo '"' . $email . ' " is Invalid'."\n";
    }

    $email = "inf at includehelp.com";
    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
         echo '"' . $email . ' " is valid'."\n";
    }
    else {
         echo '"' . $email . ' " is Invalid'."\n";
    }
    
?>

Output

"[email protected] " is valid
"inf at includehelp.com " is Invalid

Separating strings

How a normal human being validates some email addresses? The human observes some pattern in the string as well as some special characters while checking the validation of an email. The same can be done through programming. An email ID should necessarily have the character '@' and a string '.com' in a specific order. A function called preg_match() will be used for checking this order and characters.

Example 2: PHP code to validate an email address

<?php
    // A functios is created for checking validity of mail
    function mail_validation($str) {
        return (!preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
    }
    
    // Taking user input of email ID
    $a=readline('Input an email address: ');
    if(!mail_validation($a))
    {
        echo "Invalid email address.";
    }
    else{
        echo "Valid email address.";
    }
?>

Output

RUN 1:
Input an email address: [email protected]
Valid email address.

RUN 2:
Input an email address: info@includehelp
Invalid email address.

More PHP Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.