JIYIK CN >

Current Location:Home > Learning > PROGRAM > PHP >

Validating Email in PHP

Author:JIYIK Last Updated:2025/04/12 Views:

We will introduce a method to validate email addresses in PHP using filter_var()the function and FILTER_VALIDATE_EMAILfilter name ID. filter_var()The function takes an email as the first parameter and a filter name FILTER_VALIDATE_EMAILto validate the email according to the syntax in RFC 822. This method checks for a valid email format rather than a valid email.

We will also demonstrate another way to validate an email address in PHP using the FILTER_SANITIZE_EMAILand FILTER_VALIDATE_EMAILfilter name ID and the function. This method first cleans the email address and then validates the email address.fiter_var()

We will look at another method of validating emails in PHP using regular expressions. This method uses preg_match()the function to check if the email is valid based on the provided regular expression.


Validate Email in PHP using filter_var()functions andFILTER_VALIDATE_EMAIL

We can use filter_var()the filter_id function to filter a variable with a specific filter name. FILTER_VALIDATE_EMAILThe filter name specifies that the email needs to be validated. The function takes the email address as a string as the first argument and the filter id specified above as the second argument. So, we can check if the provided email is valid. The function returns the filtered data if it succeeds or returns false. The email is called valid, not in the sense that the email exists. The filter_id validates the email according to the syntax in RFC 822. We can test the validation of the email using both valid and invalid emails.

For example, create a function validateEmail()that accepts one argument $email. $emailUse the function with the variable filter_var()and specify the filter ID FILTER_VALIDATE_EMAILas the second argument. filter_var()Apply if-elsethe condition to the function. In ifthe block, display a message saying that the email is valid, and elsein the condition, display that the email is invalid. Outside the function, call the function twice. Provide the arguments in the first function call, peter.piper@iana.organd first.last@example.123
in the second call.

We can assume that the email address provided in the example is $_POSTaccessed from the form using the variable. The function in the example below is called twice. The first call passes a valid email address and the second one passes an invalid email. The second email address is invalid because it contains a number in the top-level domain. The result is obvious.

Sample code:

#php 7.x
<?php
function validateEmail($email) {
    if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "{$email}: A valid email"."<br>";
    }
    else {
        echo "{$email}: Not a valid email"."<br>";
    }
}
validateEmail('peter.piper@iana.org');
validateEmail('first.last@example.123');
?>

Output:

phppeter.piper@iana.org: A valid email 
first.last@example.123:Not a valid email

Validate email in PHP using FILTER_VALIDATE_EMAIL, , FILTER_SANITIZE_EMAILand functionsfilter_var()

We can use the additional filter name id in the first approach FILTER_SANITIZE_EMAILto remove all illegal characters from the email address. The filter name id is filter_var()the second parameter in the function where the email address is the first parameter. The function returns the sanitized email. We can use the function again to check the validity of the email address after sanitization. For this, we can FILTER_VALIDATE_EMAILfollow the first approach using the filter name id.

For example, create a variable $emailand store an email address that contains illegal characters. ram(.mugu)@exa//mple.orgStore the email as a string in the variable. Use filter_var()the function on the variable and use FILTER_SANITIZE_EMAILthe id as the second argument. Store the function in the same $emailvariable. Then, apply the statement as in the first method if-else. This time, use FILTER_VALIDATE_EMAILemail as the filter name in the function. Again, display the message.

In the following example, an email address with illegal characters is taken and filter_var()the function filters these characters and cleans the provided email. The email address provided in the example contains illegal characters such as ()and //. The function first removes these characters from the email and then validates the email.

Sample code:

#php 7.x
<?php
$email = "ram(.mugu)@exa//mple.org";
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "{$email}: A valid email"."<br>";
}
else{
    echo "{$email}:Not a valid email"."<br>";
}
?>

Output:

ram.mugu@example.org: A valid email

Use preg_match()the function to validate emails against a regular expression

We can use preg_match()the validate function to validate an email address in PHP. This method uses regular expressions as validation rules for emails. We can create regular expressions ourselves and define the rules for valid emails. The validate preg_match()function accepts two parameters where the first one is the regular expression and the second one is the email to be checked. We can use the ternary operator along with the validate function to check the validity of an email.

For example, create two variables $email_first, and $email_secon, and store two email addresses in these variables. Store valid emails first firstlast11@gmail.com, and then store invalid emails firstlast@11gmail,com. Write a function that takes one parameter validateEmail(). Name the parameter $email. Inside the function, $regexwrite a regular expression in the variable, as shown in the sample code. Then write a ternary operator where the condition to be checked is preg_match()the function. Give $regexas the first parameter and give $emailas the second parameter. Print a message that the email is valid when the condition is true and a message that the email is invalid when the condition is false. Echo the entire ternary expression. Outside the function, call validateEmail()the function twice. Use the variable in the first function call $email_firstand the variable in the second function call $email_second.

In the following example, we have written a regular expression that creates a rule to validate an email. A valid email contains a recipient name, @a symbol, a domain, and a top-level domain. The regular expression created above accepts the recipient name as an alphanumeric value. The alphabet consists of uppercase and lowercase letters. It also accepts a period. The email must have @a symbol. The domain consists of only letters. Then the email should have a period. The top-level domain should consist of only letters and should be two or three in length. The regular expression is created based on this rule. The first email is valid because it meets all the rules, but the second email is invalid. It is invalid because there are numbers in the domain name and there is no period before the top-level domain.

Sample code:

# php 7.x
<?php
$email_first = 'firstlast11@gmail.com';
$email_second ='firstlast@11gmail,com';
function validateEmail($email) {
    $regex = "/^([a-zA-Z0-9\.]+@+[a-zA-Z]+(\.)+[a-zA-Z]{2,3})$/";
    echo preg_match($regex, $email) ? "The email is valid"."<br>" :"The email is       not valid";
}
validateEmail($email_first);
validateEmail($email_second);
?>

Output:

The email is valid 
The email is not valid

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Check if a Post exists in PHP

Publish Date:2025/04/13 Views:170 Category:PHP

PHP $_POST is a super global variable that can contain key-value pairs of HTML form data submitted through the post method. We will learn different ways to check $_POST if a and contains some data in this article. These methods will use iss

PHP with Ajax

Publish Date:2025/04/13 Views:139 Category:PHP

We will use PHP and ajax by printing a simple sum of two numbers 2 and . Also, print a php array in JSON. 3 object We will also use PHP with ajax by getting the HTML formatted output from the number division in PHP. Printing simple addition

Store Div Id in PHP variable and pass it to JavaScript

Publish Date:2025/04/13 Views:51 Category:PHP

This article shows you how to div id store a in a PHP variable and pass it to JavaScript code. We will answer the following questions. What is div id ? How to div id store in a PHP variable? How to pass variables to JavaScript code? Let’s

Returns the article tag with ID from the action page

Publish Date:2025/04/13 Views:80 Category:PHP

Let's say you're in a login form and you enter the wrong information; in this case, you probably want to go back to the login page. PHP has a built-in function header() to redirect a page to a specific page. But what if the login page is at

Switching PHP versions on Ubuntu

Publish Date:2025/04/13 Views:78 Category:PHP

Different tasks may require running multiple versions of PHP. You may need to switch PHP versions by running two sites on the same server or testing older versions of code using outdated methods. We can switch PHP versions on Ubuntu using t

Resizing images in PHP

Publish Date:2025/04/13 Views:155 Category:PHP

In this tutorial article, we will discuss about resizing images in PHP. Load the image before resizing Before we can resize an image, we must first load it as an image resource in our script. This is file_get_contents() different from using

PHP upload image

Publish Date:2025/04/13 Views:61 Category:PHP

We can upload images in PHP using simple file upload operation, but first, php.ini file upload should be enabled from Files. This tutorial demonstrates how to upload images in PHP. php.ini Enable file upload from file in PHP to upload image

Creating a signature from Hash_hmac() and Sha256 in PHP

Publish Date:2025/04/13 Views:107 Category:PHP

PHP has one of the best encryption functions for data security. Hash_hmac() The encrypt function is one of the most famous encryptors. We'll show you how to use hash_hmac and sha256 encryptors to create 安全签名 one that you can store i

Updating PHP 7.x to 7.4 on CentOS

Publish Date:2025/04/13 Views:131 Category:PHP

This article shows the steps to update the PHP version from 7.x version to 7.4 in CentOS. How to Update PHP from 7.X to 7.4 in CentOS Update operating system packages. yum update -y Check your PHP version in CentOS. php -v Prints a list of

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial