Guides
Last updated
August 3, 2023

How to Validate Email Addresses with PHP and Regular Expressions

Shyam Purkayastha

Table of Contents:

Get your free
Email Validation
API key now
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required

When leveraging email addresses for digital marketing, the famous idiom “Garbage in, garbage out” is well applicable. If you do not ascertain the validity and legitimacy of the email addresses you capture, your marketing campaigns will fail miserably. Email is still a widely popular means of outreach. Therefore, you must pay attention to validating email addresses to improve your business metrics.

The post presents a few different methods to validate email addresses in PHP code. As a web developer, you can use these code snippets within a PHP-based web application backend that accepts opt-in forms or processes other data passed on from the frontend web portals, likely to contain email addresses.

Before you check out these options, ensure that you have a working development environment already set up with the latest version of PHP8. You should also have an API testing tool like Postman or the cURL utility to test the code via an API interface.

Related: AJAX PHP Email validation

Email Address Validation with In-built PHP Functions

There are several ways to validate emails using PHP. However, as a simple and quick option, most developers opt for the inbuild PHP way of using filter_var(‘email, FILTER_VALIDATE_EMAIL).

Open your favorite IDE and create a file named email.php. Next, let’s define an EmailValidation class in PHP.


header('Content-type: application/json');
class EmailValidation
{
public $email;

public function __construct()
{
$this->apiKey = 'YOUR_ABSTRACT_CODE';
$this->email = $_POST['email'] ?? '';
}

}

?>

This class defines a public property $email that stores the email address to be validated. The email address is passed as part of a POST API call.

Add a method getRequest( ) to send an API request to the PHP code.


public function getRequest()
{
if (empty($this->email)) {
echo json_encode(array('status' => false, 'message' => 'Invalid request'));
http_response_code(400);
exit;
}

echo $this->withPHPFilter($this->email);
}

This method will pass the email address to a private method withPHPFIlter( ) for validation. Add this private method to the EmailValidation class. 


private function withPhpFilter($email)
{
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
http_response_code(200);
return json_encode(array('status' => true, 'message' => 'Valid email'));
} else {
http_response_code(400);
return json_encode(array('status' => false, 'message' => 'Invalid email'));
}
}
Let’s send your first free
Email Validation
call
See why the best developers build on Abstract
Get your free api

This method leverages the PHP’s inbuilt function filter_var( ) to check for the valid email format to return a success (200 OK) or a failure (400 Bad Request).

To make the class methods accessible through an API, add this code outside the EmailValdiation class definition to create an instance of it that accepts an incoming API request.


$validate = new EmailValidation();
$validate->getRequest();

Here is the complete code for defining the EmailValidation class, and its instance invocation.


header('Content-type: application/json');
class EmailValidation
{
public $email;

public function __construct()
{
$this->apiKey = 'YOUR_ABSTRACT_CODE';
$this->email = $_POST['email'] ?? '';
}

public function getRequest()
{
if (empty($this->email)) {
echo json_encode(array('status' => false, 'message' => 'Invalid request'));
http_response_code(400);
exit;
}

echo $this->withPHPFilter($this->email);
}

private function withPhpFilter($email)
{
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
http_response_code(200);
return json_encode(array('status' => true, 'message' => 'Valid email'));
} else {
http_response_code(400);
return json_encode(array('status' => false, 'message' => 'Invalid email'));
}
}
}

$validate = new EmailValidation();
$validate->getRequest();

?>

Now, we are ready to test this code. You must run this PHP code as a web server by launching it from a command line terminal.


php -S 127.0.0.1:8000

Make sure to run this command in the same directory where you have saved the email.php file. Now, the PHP web server is running and the URL is http://127.0.0.1:8000/email.php

If you launch the Postman API tool and fire up the API with a valid email, you should see an API response with the “Valid email” message.

The filter_var( ) can also catch a wrongly formatted email address.

Validating Email Addresses with Regular Expressions in PHP

The in-built function approach can validate an email address based on the standard format. However, for checking custom email rules, the regular expression is the best choice.

PHP has in-built support for regular expressions through the preg_match( ) function. Let’s use it to build a matching pattern for an email address.

Default PHP Email Regex Validation

Let’s modify the EmailValidation class to add regular expression-based validation. Add a new private method withRegEx( ) to validate the email address with the preg_match( ) function.


private function withRegex($email)
{
$regex = '/^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$/';

if (preg_match($regex, $email)) {
http_response_code(200);
return json_encode(array('status' => false, 'message' => 'Valid email'));
} else {
http_response_code(400);
return json_encode(array('status' => false, 'message' => 'Invalid email'));
}
}

Also, you must modify the last line of  getRequest( ) method to call withRegex( ) instead of withPHPFiilter( ).

If you test the API, you should get the same behavior for email address validation as the in-built function in the above example.

Custom PHP Email Regex Validation

Regular expression validation takes the cake when dealing with custom rules for email IDs. For example, if you want to ensure that the submitted email address should not have an underscore ‘_’ character in the email ID, you can modify the regex pattern to omit that.

The existing regex pattern defined in the withRegex( ) method allows alphanumeric characters along with ‘_” , “.” and “-” characters. If you want to omit the underscore, then you must define a regex pattern like this.


$regex = '/^[a-zA-Z0-9+.-]+@[a-zA-Z0-9.-]+$/';

Replace this pattern in the withRegex( ) method and save the file. Let’s test it out.

The API will now return a failure for an email address with an underscore character in the ID.

Similarly, you can define finre grained, custom regex rules to omit illegal characters from the email. That’s the power of regular expression. However, this kind of email address validation is also limited to the address format.

Validating Email Address with API

The PHP in-built and regex functions are great options for validating email addresses. But if your business really depends on the legitimacy of email addresses, this becomes mission critical. Under these circumstances, merely validating the email address format is not enough. You need to validate the email address to ensure that the email exists. Moreover, it should belong to the persona you are targeting, and its underlying domain and SMTP servers are also valid.

These advanced validations can only be done via an API service. Abstract API offers an Email Validation and Verification API to solve this problem. It goes beyond the simple addressing patterns to validate email based on the email’s domain and SMTP checks.

Check out the capabilities of this API by signing up for an Abstract account. You can access the API dashboard to make a test API call with any email address. Make sure to take note of your API key.

This API provides deeper insights about an email address, such as the deliverability of the email domain and the validity of the MX records, over and above the basic format validation checks. You can check the documentation on the API page. This API gives you 100 free API calls per month.

Integrating this API in any PHP code using the curl library is quite straightforward. Let’s add one more private method withAbstract( ) to the EmailValidation class.


private function withAbstract($email)
{
$url = "https://emailvalidation.abstractapi.com/v1/?api_key=" . $this->apiKey . "&email=" . $email;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'Accept: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
$response = json_decode($response, true);

if (($response['deliverability'] !== 'DELIVERABLE')) {
http_response_code(400);
return json_encode(array('status' => false, 'message' => 'Email is Undeliverable'));
exit;
}

if (!$response['is_valid_format']['value']) {
http_response_code(400);
return json_encode(array('status' => false, 'message' => 'Invalid email format'));
exit;
}

if (!$response['is_mx_found']['value']) {
http_response_code(400);
return json_encode(array('status' => false, 'message' => 'Invalid email domain'));
exit;
}

if ($response['is_disposable_email']['value'] == true) {
http_response_code(400);
return json_encode(array('status' => false, 'message' => 'Disposable email'));
exit;
}

http_response_code(200);
return json_encode(array('status' => true, 'message' => 'Valid email'));
exit;
}

This method calls the Abstract Email validation API and checks the response for

  1. Deliverability, to check if the email is deliverable or not
  2. Format, to check if the email address has the right format or not
  3. MX Record, to check if the SMTP domain configuration is email address exists or not
  4. Non-disposablity, to check if the email address is a permanent address or not.

If any of these checks fail, the email address is marked invalid. You can also see that the API response can now indicate additional error messages for each of these failures.

You need the API key to call the Abstract API from within this method. Add the API key as a public class property on the EmailValidation class.


public $apiKey = “”;

Make sure to replace the value of $apiKey with the actual key allotted to you in your Abstract API account.

Make one more update in the getRequest( ) method to replace the call to withRegex( ) with withAbstract( ). Now you are ready to test the PHP-hosted API.

Let’s test with a fake email address.

As you can see, the email address format is valid. Still, the email address does not point to a legitimate mail domain. Therefore, Abstract API will validate the email to indicate that it is undeliverable. The in-built PHP function and regular expression validation would never be able to catch such validation issues in email addresses. 

You can combine the Abstract API with your custom regex function filters to build a foolproof PHP email validation logic. In this can, you can define another method that performs the regex validation of the email id and then lets the Abstract API validate the deliverability and other aspects of the email address. 

We encourage you to extend the EmailValidation PHP class to add this new method for combining custom regex validation with Abstract API email validation to build your own rule for the valid email address. Give it a try, and you will realize how easy it is to build custom email validation logic in PHP without writing much code.

FAQ

How Do I Validate Email Addresses in PHP?

PHP provides a simple validation function for detecting valid email addresses. Using the in-built filter_var( ) function, you can validate any email address for the standard format checks, such as the presence of the email id, the ‘@’ symbol, and the domain part. This is a quick and easy approach to validating email addresses. However, it is ineffective in detecting fake email addresses that appear to be formatted correctly but are undeliverable. For such advanced validation, you can use the Abstract Email Validation API to detect fake email addresses based on database lookup and real-time SMTP checks on email domains.

What Validations Are Possible for Email using PHP Regular Expression?

The preg_match( ) is an in-built function in PHP, for performing regular expression matches. Email addresses have a standardized format. Therefore, regular expression matches can be used to validate the format of any email address. Apart from the standard norms for checking the email id, ‘@’ symbol, and the domain part of the email address, regular expressions can enforce custom rules for email ids that include or exclude certain characters. For example, it is possible to build a regular expression that invalidates any email address that contains an underscore ( ‘_’ ) character in the email id.

How To Check if an Email Address is Legitimate?

The sure-shot way of checking for valid email addresses is to send a test e-mail to those addresses. However, this may not be the most scalable and speedier approach. Also, this approach does not take into account email addresses that are genuine but are temporary or role-based mail aliases. You can leverage the Abstract Email validation API for foolproof validation of any email address. This API provides more profound insights about validating emails, from basic format checks to the MX records and deliverability status. This API helps you profile email addresses and filter out any invalid email addresses based on multiple criteria.

Shyam Purkayastha

Shyam Purkayastha is a proficient web developer and PHP maestro, renowned for his expertise in API creation and integration. His deep knowledge of PHP scripting and backend development enables him to build scalable server-side applications. Shyam is particularly passionate about RESTful API design, significantly enhancing web service functionality and data interoperability.

Get your free
Email Validation
key now
See why the best developers build on Abstract
get started for free

Related Articles

Get your free
Email Validation
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required