Guide to email validation in PHP: filter_var(), regex and API methods


Invalid email addresses come in various forms; some are harder to spot than others. One thing they have in common, though, is that sending to them can spell disaster for your deliverability.
But it’s not all doom and gloom—email list hygiene is just another important aspect of email sending that you need to consider. And with the right tools and strategies, you can maintain a healthy list and avoid any of the issues that invalid emails can present. That’s where email validation and verification come in.
In this guide, we’ll cover why email validation is important and how you can validate emails in PHP using 3 methods: native PHP functions (filter_var()), regex, and an API.
Why email validation is a must, not a maybe
OK, so we know that email address validation is important, but why? Well, imagine you have a sign-up form with no email validation. It allows any kind of email address to be entered, whether an email address with improper syntax or a bot using an email with a disposable domain.
Let them all in and you’ll soon have a messy database filled with invalid emails, which will be a pain to clean up. Plus, your email sending will be impacted in numerous ways. Here’s a quick look at how:
Increased bounce rates due to email addresses with non-existent mailboxes
Decreased engagement due to sending to invalid emails that will never receive or open your emails
Potential for your sender reputation to be impacted and your IP address or domain to be added to a blocklist if you regularly send to invalid email addresses or spam traps
User experience is affected if a user mistakenly enters a wrong email address. They’ll never receive your important communications, plus they’ll face difficulty accessing their account and resetting their password
Increased bounce rates, infiltration of database, and abuse of platform by fake bot accounts
Wasted money and resources by sending to invalid emails—even if they don’t exist, they still count towards your billing
Skewed metrics that lead to misinformed decision-making and strategy
Method 1: Validating emails with filter_var()
PHP’s native filter_var() function is used to filter a variable with a specified function. Here’s the syntax for the function:
filter_var(var, filtername, options)
var: The variable to be filtered; this is required
filtername: The filter you want to use; this is optional but the default is FILTER_DEFAULT, which results in no filtering
options: The flags or options you want to use to check each filter for; this is optional
How to use filter_var(), FILTER_VALIDATE_EMAIL and FILTER_SANITIZE_EMAIL
To validate emails, you’ll use the FILTER_VALIDATE_EMAIL and FILTER_SANITIZE_EMAIL filters.
FILTER_VALIDATE_EMAIL checks that the email address complies with PHP standards for the email’s format. Specifically, it checks that the email address contains a prefix or username and the '@' symbol followed by the domain part, which consists of the domain name and top-level domain (TLD).
FILTER_SANITIZE_EMAIL “sanitizes” the email of any unsupported characters. This includes spaces, commas and all characters except for !#$%&'*+-=?^_`{|}~@.[].
So you can use a combination of the two filters to check the syntax and remove non-permitted characters before allowing the email address to be submitted or sending it for further verification (more on that later).
Here’s a simple PHP code example:
<?php
// An email with an invalid (non-ASCII) character
$email = "userΩ@example.com";
// Remove invalid characters
$sanitized_email = filter_var($email, FILTER_SANITIZE_EMAIL);
// Return sanitized email address
echo "Sanitized Email: $sanitized_email";
// Checks sanitized email’s format
if (filter_var($sanitized_email, FILTER_VALIDATE_EMAIL)) {
// If email follows correct syntax, return valid message, otherwise return invalid message
echo "Valid email address.";
} else {
echo "Invalid email address.";
}
You can also remove the sanitization filter and simply validate the email address syntax. You just need to remove the FILTER_SANITIZE_EMAIL function and use the correct variable for the email address:
<?php
// The email address we want to validate
$email = "[email protected]";
// Checks the email address format
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
// If email follows correct syntax, return valid message, otherwise, return invalid message
echo "Valid email address.";
} else {
echo "Invalid email address.";
}
Pros of using filter_var() to validate emails
1. It’s relatively simple to implement. As you can see from the code examples above, you can use filter_var() to validate email addresses with just a few lines of code.
2. It’s a very accurate method of validation for checking email address syntax and non-permitted characters.
3. It’s a built-in PHP function, so there’s no need for external libraries.
Cons of using filter_var() to validate emails
1. It will only check whether an email address is structured correctly; it won’t perform any SMTP or DNS checks to check for an MX record and verify that the email address is deliverable and unlikely to bounce.
2. It can be too strict! The filter_var() function has limited support for international email addresses that use special characters (like in our example above that contains the Greek character ‘Ω’). It also doesn’t support some newer TLDs.
3. There is a lack of context available with error messages. The validation will simply return ‘true’ or ‘false’ and won’t tell you why the email failed.
Method 2: Validating emails with regular expressions (regex)
A regular expression, or regex, is a super powerful way to match patterns in a string. You can use it to search for and manipulate text, extract data, or—you guessed it—validate and filter email addresses.
Regex is useful because it allows you to create custom specifications for your email address validation. For example, you could block email addresses that match specific domains or set a minimum character length for the email username.
Here’s the syntax for PHP regular expressions:
$pattern = "/mailercheck/i";
$pattern: The variable for your pattern
/ = The delimiter, which can be any character that isn’t a letter, number, space or backslash. A forward slash is commonly used, but if your regex contains a forward slash, you can choose something else
mailercheck: In this example, ‘mailercheck’ is the pattern we have defined. So the function will check for any string that matches ‘mailercheck’
i: The modifier that makes the check case-insensitive
How to use regex to validate emails
There are numerous functions that you can use with regex, but the one we’re going to focus on is preg_match(). preg_match() checks the string for the defined pattern and then returns 1 if the pattern is found and 0 if it isn’t.
Here’s a simple regex code example:
<?php
function isValidEmail($email) {
// Define a simple regex pattern for email validation
$pattern = '/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/';
// Use preg_match() to check if the email matches the pattern
if (preg_match($pattern, $email)) {
return "Valid email.";
} else {
return "Invalid email format.";
}
}
Here, the pattern we’ve defined (/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/) includes the characters that are allowed for each part of the email address. We then use the preg_match() function to check that the $email matches the $pattern.
This example uses a basic character sequence, but you can customize the pattern as much as you want. RegExr is a good resource to learn more about patterns, create your own, and access ready-made, community-built patterns you can use in your own projects.
Pros of using regex to validate emails
1. It’s highly customizable, giving you many more filtering options than filter_var().
2. You can use it to enforce specific policies or address security concerns, for example, only allowing internal email addresses.
3. It’s more flexible than filter_var(); you can define patterns that allow for unusual email structures or newer TLDs.
Cons of using regex to validate emails
1. It can become extremely complex, and it’s quite difficult to get the right regex.
2. It’s easy to block or allow the wrong email addresses, and it needs a lot of testing and tweaking.
3. It will only tell you if the email address matches or doesn’t match the pattern you have defined. In other words, it’s only good for syntax checks and filtering domains—it won’t tell you if the email address is deliverable or risky to send to.
Method 3: Using an email verification API
We’ve looked at 2 PHP email validation methods, and now we’re shifting the focus to email verification. While email validation checks that the email address is formatted according to the correct email address structure, email verification performs other checks as well to see if the email is actually real and can be delivered to.
Here’s a quick example:
This email address will pass PHP filter_var() and regex validation. It follows all of the standards for the structure of an email address. But the mailbox doesn’t exist. This is where email verification steps in.

An email verification API will check for syntax issues and typos and it will also check:
If the mailbox exists: An email can be syntactically valid but not exist, so if you send to it, it will hard bounce
If the mailbox is full: These emails will soft bounce, so you can exclude them while they are full
If the domain is disposable: Disposable or temporary domains are used by people who want to avoid receiving emails when they sign up. They’ll likely never open anything you send them, and the mailbox will become completely inactive shortly after creation. What’s more, disposable domains are often used by bots
If the domain is catch-all: Catch-all domains will accept any incoming emails, even if the email address doesn’t exist. If the email address doesn’t exist, it will go to a catch-all mailbox, where it’s likely it won’t be opened. Lots of businesses use catch-all domains, so you should send with caution and keep an eye on engagement
If the email is role-based: Role-based emails belong to a department or team (like [email protected]) rather than an individual. Again, lots of businesses use these, so you should send with caution and monitor engagement
In other words, you get tons more information about the state of the email address that you can use to segment and manage your email list. And, with an email verification API, you can run the check at the point of collection to stop invalid emails from ever entering your database or to filter them more easily because it performs the check in real time.
How to use an API to verify email addresses
Before you get started, you’ll need to choose an email verification service with an API. For this example, we’re using MailerCheck! MailerCheck performs all of the checks mentioned above, and you can verify emails by uploading a list or using the API.
You can sign up for a free account and get 200 free credits to try it out.
So let’s get started! You can use your favorite HTTP/REST library to make HTTP calls. For this example, we’ll use Guzzle.
1. Create an API token in MailerCheck. In the main menu, click API tokens and then click Generate token. Add a name for your API token and, once again, click Generate token. Copy or download your token.
2. Configure your frontend to submit the email to your backend for verification. When the email is submitted on the frontend, it needs to be sent with Javascript to the backend and then via the API to MailerCheck to be verified.
Here’s an example of the code you’ll need for the script element of your HTML page to do this:
< script >
document.querySelector(`#signupForm`).addEventListener('submit', function(event) {
event.preventDefault(); // Prevent the form from submitting
const emailInput = document.querySelector(`#email`);
const errorMessage = document.querySelector(`#error-message`);
fetch('http://localhost/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: emailInput.value
})
})
.then(response => response.json())
.then(result => {
console.log(result);
if (result.success) {
errorMessage.textContent = ''; // Clear any previous error message
alert('Email is valid! Form submitted.');
} else {
errorMessage.textContent = result.text || 'Please enter a valid email address.';
}
});
}); <
/script>
2. Configure your backend to send the email address to MailerCheck for verification and return the results. In the example below, we’re using the phpdotenv package for environment variables. You should always use variables to conceal sensitive information like your API keys.
.env file example:
MAILERCHECK_API_KEY=your_mailercheck_api_key_here
<?php
require "vendor/autoload.php";
use Dotenv\Dotenv;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
// Load environment variables
$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$input = json_decode(file_get_contents("php://input"), true);
$email = $input["email"] ?? "";
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo json_encode([
"success" => false,
"text" => "Invalid email format.",
"color" => "red",
]);
exit();
}
$apiKey = getenv("MAILERCHECK_API_KEY"); // Get the API key from the environment variable
try {
$client = new Client([
'base_uri' => 'https://api.mailercheck.com/',
'headers' => [
'Authorization' => "Bearer $apiKey",
'Accept' => 'application/json',
]
]);
$response = $client->post("api/check/single", [
'query' => [
'email' => $email
]
]);
$result = json_decode($response->getBody(), true);
if (!empty($result['status']) && $result['status'] === 'valid') {
echo json_encode([
"success" => true,
"text" => "Email is valid.",
"color" => "green",
]);
} else {
echo json_encode([
"success" => false,
"text" => "Email is invalid.",
"color" => "red",
]);
}
} catch (RequestException $e) {
error_log("Request error: " . $e->getMessage());
echo json_encode([
"success" => false,
"text" => "An error occurred during validation.",
"color" => "red",
]);
}
} else {
echo json_encode([
"success" => false,
"text" => "Invalid request method.",
"color" => "red",
]);
}
We’re also using PHP filter_var() here to catch emails with the wrong syntax before they are submitted for verification. This helps to catch simple typos without having to use the API and your email verification credits. Here’s what we get with the code examples above and an email address that gets caught by filter_var().

And here’s the result we get for a valid email address:

And for an invalid email address that gets checked with MailerCheck, here is the result:

And the response from the MailerCheck API:

Using the API, we can actually see why the email address is invalid. In this case, the mailbox doesn’t exist. You can use these results to block or exclude certain types of emails, or use the data to segment your email list and handle them however you want.
For example, if you’re sending marketing emails, you could segment catch-all and role-based email addresses to monitor engagement more effectively and filter out inactive subscribers.
Why use an API for PHP email validation?
Yes, we’re fans of the API—and not just because we have one. Here’s why an email verification API reigns supreme.
1. It checks more than email address syntax
An email verification API does so much more than validate that an email address is correctly formatted. Without it, simple PHP email validation would let through:
1. Non-existent email addresses.
2. Disposable or temporary email domains.
3. Undeliverable emails that are blocking incoming mail or are full.
4. Role-based emails that don’t belong to a person.
5. Catch-all emails that may or may not exist.
And even if you don’t want to block all of these types of emails, with an email verification API you have the ability to handle them as you see fit.
2. It blocks disposable emails for you
There are thousands upon thousands upon thousands of disposable email domains. That means, although it's possible to block whichever and however many domains you like with regex, it’s impossible to block them all with this method. An email verification API has the processes in place to check an email address against the thousands of disposable domains quickly and without any strain on your system.
3. It’s scalable and easy to maintain
An email verification API is built to handle high volumes of requests and will easily scale with your demands. There’s also no need to update, adjust and maintain complex regex patterns. The API does all of the verification work for you.
Best practices for email validation in PHP
1. Use a combination of PHP validation methods
Depending on your use case, a combination of filter_var() or regex and an email verification API could make for a super effective approach. You can easily block syntactically incorrect email addresses and prompt the user to enter a valid email address before ever submitting to the API. Using a combination of methods covers you on all bases and optimizes your API usage.
2. Use email validation to improve the user experience
Validating emails isn’t just about maintaining good deliverability and keeping your email lists clean. It also improves the user experience by letting users know when they’ve entered an invalid email address. Return feedback to the user via the UI so they can correct their mistakes. For an even more solid approach, send an email verification message as well.
3. Avoid regex if you’re not 100% sure
Regex gets complex fast, and it’s prone to errors if you’re not careful. Using filter_var() and an API is a strong solution that’s much easier to maintain. If you do opt for regex, keep your patterns as readable and simple as possible. If necessary, split the regex into smaller components.
That’s email validation in PHP
Whether you go with filter_var(), regex, API, or some combination of the three, email validation is the crucial key to maintaining great deliverability and a happy, clean database of emails that won’t bring you to tears.
If you want to go beyond validating email syntax—and you should, because trust us, disposable emails and spam traps are no bueno—an email verification API will give you the checks and insights you need to handle every type of email address.
Ready to give MailerCheck's API a go?
Sign up now and get 200 email verification credits free. Verify your emails in-app or use the code examples above to test out email verification via the API.
