Validating email addresses in PHP is a fundamental step for maintaining data quality and ensuring reliable communication. We will explore four common implementation methods with code examples, examine their inherent pitfalls, and see how Abstract API overcomes these limitations.
How to Implement Email Validation in PHP
PHP offers several methods to validate email address formats. Each approach provides a different level of strictness and complexity, from simple built-in functions to comprehensive, RFC-compliant libraries.
PHP's Internal Parser with `filter_var()`
This method uses PHP’s built-in "filter_var()" function with the "FILTER_VALIDATE_EMAIL" filter. It leverages the same internal parser that PHP's engine uses to build outbound addresses. This process correctly rejects invalid formats like comments or unescaped quoted strings. The code first removes any extra whitespace from the input with the "trim()" function before the validation occurs.
$email = trim($input);
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
…continue…
}
IDN-Aware Validation with `idn_to_ascii`
This technique enhances "filter_var()" to support Internationalized Domain Names (IDNs), such as those with non-Latin characters. The process involves three steps. First, the email address splits into a local part and a domain part. Second, the "idn_to_ascii()" function converts the domain into its ASCII-compatible Punycode equivalent. This conversion is necessary because "filter_var()" alone does not support Unicode domains, a gap noted in community discussion. Finally, the parts reassemble and pass to "filter_var()" for validation. This method requires the "intl" PHP extension.
list($local, $domain) = explode('@', $email, 2);
$domainAscii = idn_to_ascii($domain, IDNA_DEFAULT, INTL_IDNA_VARIANT_UTS46);
$emailReassembled = $local . '@' . $domainAscii;
if (filter_var($emailReassembled, FILTER_VALIDATE_EMAIL)) {
…continue…
}
Comprehensive Validation with Egulias/EmailValidator
For a more robust, RFC-compliant check, you can use the Egulias/EmailValidator library, which is installable via Composer. This component provides a thorough implementation of RFC 5321, 5322, 6531, and 6532 grammars, with full UTF-8 support. To perform a check, you instantiate the "EmailValidator" class and call its "isValid()" method with the email and a validation strategy, such as "RFCValidation". The library also offers other strategies, including "DNSCheckValidation" and "SpoofCheck", which can be chained together for multi-layered validation.
use Egulias\EmailValidator\EmailValidator;
use Egulias\EmailValidator\Validation\RFCValidation;
$validator = new EmailValidator();
if ($validator->isValid($email, new RFCValidation())) { … }
Format Check with DNS MX Lookup
This method adds a layer of verification by checking a domain's Mail Exchange (MX) records. After a successful syntax validation with a method like "filter_var()", the code extracts the domain from the email address. It then uses the "checkdnsrr()" function to query for MX records associated with that domain. A successful lookup confirms the domain is configured to receive email, which helps catch typos like "user@gmil.com" instead of "user@gmail.com". The check is efficient because the OS resolver caches the result.
list(, $domain) = explode('@', $email, 2);
if (checkdnsrr($domain, 'MX')) {
…address is at least routable…
}
Challenges of Email Validation in PHP
While PHP provides several validation methods, they present significant challenges. These range from incomplete RFC compliance and limited character support to the inability to confirm an email address's actual deliverability.
- The
filter_var()
function fails to support complex but valid formats allowed by RFC 5322, like quoted local parts. This leads to false negatives for valid addresses and false positives for some malformed ones. - PHP's built-in
filter_var()
function is ASCII-centric and rejects addresses with Unicode characters. Even with idn_to_ascii
, the validation still fails if the local part of the email contains non-ASCII characters. - A successful syntax check with
filter_var()
does not guarantee deliverability. The function approves addresses with non-existent or misspelled domains, which requires a separate DNS MX lookup with checkdnsrr()
to catch. - The
filter_var()
function contains hard-coded policy choices that cannot be easily modified. To extend or relax these rules, developers must wrap the function with custom logic for regex, IDN handling, and DNS checks.
Validate Emails with Abstract API
Implement email validation in your PHP application to prevent bad signups and protect your data.
Get started for free
How Abstract API Handles Email Validation in PHP
Abstract API addresses the core weaknesses of traditional methods by the aggregation of multiple validation layers into a single HTTPS call.
- It identifies and flags disposable, role-based, and catch-all addresses, which simple regex checks often miss.
- The API provides an auto-correct suggestion for common typographical errors in email addresses.
- It performs MX and SMTP tests on its own servers, which removes latency and potential firewall issues from your application.
- You receive continuous updates to validation rules, so you do not need to maintain a custom rule set.
How to Add Abstract API to Your Dev Environment
Once you know Abstract’s capabilities, you can add its email validation API to your project with ease. The process requires just a few steps to get the client ready in your development environment.
- Use Composer to add the required package to your project dependencies.
- Sign up at Abstract and generate an Email Validation API key from your dashboard.
- Add your key to an environment variable, such as ABSTRACT_API_KEY, or place it in a secure configuration file.
- Require the Composer autoloader in your application’s bootstrap file.
- Configure the client with your API key so it can authenticate requests.
- Call the verify method wherever you need to check an email address.
Sample Email Validation Implementation with Abstract API
The following PHP code demonstrates a simple validation request. It sends an email address that contains a typo, "john.doe@gmial.com", to the API. The logic then checks the deliverability status and looks for an auto-correct suggestion, which allows you to either flag the email or prompt the user with the corrected version.
<?php
require 'vendor/autoload.php';
use Abstractapi\EmailValidation\AbstractEmailValidation;
AbstractEmailValidation::configure($_ENV['ABSTRACT_API_KEY']);
$response = AbstractEmailValidation::verify('john.doe@gmial.com');
if ($response->deliverability !== 'DELIVERABLE') {
// flag or reject
}
if ($response->auto_correct) {
// suggest $response->auto_correct to user
}
?>
The API returns a comprehensive JSON object with the validation results. As shown in the sample output below, the API correctly identifies the email as "UNDELIVERABLE", provides a "quality_score" of "0.15", and offers the "auto_correct" suggestion "john.doe@gmail.com". It also includes boolean flags for disposable, role-based, and catch-all addresses to enable more granular rules.
{
"email": "john.doe@gmial.com",
"auto_correct": "john.doe@gmail.com",
"deliverability": "UNDELIVERABLE",
"quality_score": "0.15",
"is_valid_format": true,
"is_free_email": true,
"is_disposable_email": false,
"is_role_email": false,
"is_catchall_email": false,
"is_mx_found": false,
"is_smtp_valid": false
}
Final Thoughts
Traditional validation methods often fail because they miss disposable domains and cannot correct typos. Slow SMTP and DNS checks also create latency. Abstract API solves these issues with a single, fast API call that provides typo suggestions, deliverability scores, and detailed flags. For reliable user email validation, consider an account on Abstract API to get your free API key.
Validate Emails with Abstract API
Add email validation to your PHP code to prevent bad sign-ups and keep your data clean.
Get started for free