Article
PHP Email Validation with filter_var: What It Catches and What It Misses
By Unlimited Verifier Team ·

Summary
Use PHP's filter_var with FILTER_VALIDATE_EMAIL as a fast syntax gate, trimming input first. It only checks format, so pair it with a DNS check and a mailbox-level verifier to find addresses that won't actually receive mail.To validate an email in PHP with filter_var, call filter_var($email, FILTER_VALIDATE_EMAIL). It returns the address when the format is valid and false when it isn't. It never checks whether the mailbox exists, so add a DNS check for each domain and a mailbox-level verifier for lists.
Most PHP projects start with filter_var because it ships with the language and needs no Composer package. It's a sound first gate for catching typos on a signup form. It stops being enough once you care whether mail arrives, whether a list is compliant, or whether you're cleaning 45,000 contacts from a CRM export. This guide covers where the built-in check ends, how to layer DNS checks on top, and how to run a large list through Unlimited Verifier from a PHP workflow. For the wider picture, start with our real-time email validation pillar.
Quick answer
- Use
filter_var($email, FILTER_VALIDATE_EMAIL)as a first gate. It checks format only and needs no network access. - Trim input, then add a DNS check. Look for an MX record, then fall back to an A record, as RFC 5321 describes.
- Don't treat a pass as deliverable.
filter_varcan't see whether a mailbox exists, is disposable, or sits on a catch-all domain. - Verify whole lists separately. Export a CSV, verify it, and re-import only the Valid rows. For ongoing checks, the API accepts bulk batches of up to 10,000 emails per request.
- Fail open on DNS timeouts. A resolver hiccup is not evidence that an address is invalid.
What does FILTER_VALIDATE_EMAIL actually check?
FILTER_VALIDATE_EMAIL is a validation filter in PHP's filter extension, documented in the PHP filter manual. It tests the string against a pattern based on internet email syntax. It never contacts a mail server, so it sees the shape of an address and nothing else.
That narrow scope has three practical consequences:
- Syntactically valid addresses can still be dead. An address on a domain that was never registered passes the check.
- Typos on real domains pass.
jane@gmial.comis well-formed. Whether it has working mail servers depends on who registered that typo domain. A DNS check can't tell a parked typo domain from a real business, so it won't catch every typo. - Surrounding whitespace isn't your problem to ignore. Addresses copied from spreadsheets and PDFs often carry hidden spaces. The filter isn't designed to strip them, so trim before you validate.
RFC 3696, an informational guide to checking names and addresses, makes the broader point: a syntax check can't tell you whether an address is in use. Behaviour around Unicode addresses has also changed across PHP versions. The FILTER_FLAG_EMAIL_UNICODE flag arrived in PHP 7.1, so confirm the details against the manual for your version.
Run this snippet against your own sample addresses to see the behaviour:
<?php
$tests = [
'jane.doe+news@example.com',
' jane@example.com',
'jane@gmial.com',
'jane@localhost',
];
foreach ($tests as $t) {
$ok = filter_var($t, FILTER_VALIDATE_EMAIL) !== false;
printf("%-28s %s\n", "'$t'", $ok ? 'syntax OK' : 'rejected');
}
The gap between "syntax OK" and "reaches a human" is where most list problems live. Use your own data to measure that gap rather than trusting a sample.
Bottom line: filter_var answers "is this shaped like an email address?" It doesn't answer "can I reach this person?"
How do you add PHP email validation with filter_var step by step?
Build validation as a short pipeline where each step is cheap and fails in a predictable way. Order matters: run the cheapest checks first, so DNS lookups only run on input that already looks right.
- Trim and bound the input. Remove surrounding whitespace, reject empty strings, and cap length at 254 characters. That's the practical forward-path limit most guidance uses, and RFC 5321 sets the underlying path limit at 256 octets.
- Run
filter_var. Reject anything that returnsfalse. - Split on the last
@. Usestrrposso the domain is always the text after the final@. A plus tag or quoted local part can contain other characters, so don't split on the first@. - Check DNS. Look for an MX record first. If none exists, check for an A record, since RFC 5321 describes delivery to the address record when no MX is published (RFC 5321).
- Cache the result per domain. Domain-level answers change slowly, so caching for a few hours avoids repeating lookups for
gmail.comthousands of times. - Decide what a failure means. Treat "no records" as invalid. Treat a timeout as unknown, and let the signup through.
Here is a function that implements steps 1 through 4:
<?php
function isPlausibleEmail(string $raw): bool
{
$email = trim($raw);
if ($email === '' || strlen($email) > 254) {
return false;
}
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
return false;
}
$domain = substr($email, strrpos($email, '@') + 1);
// MX first, then the A-record fallback described in RFC 5321
if (checkdnsrr($domain, 'MX')) {
return true;
}
return checkdnsrr($domain, 'A');
}
The most important design decision is step 6. checkdnsrr() returns only a boolean, so it can't distinguish "this domain doesn't exist" from "the resolver timed out." If your signup form rejects every timeout, a DNS hiccup at peak traffic will lock real customers out. Log the failure, let the user through, and re-check the address in a background job.
For a fuller treatment of MX lookups, including alternatives to checkdnsrr(), see how to check MX records programmatically.
Bottom line: Run cheap checks first, cache DNS results by domain, and never treat a timeout as a rejection.
How do you test the validator on your own addresses?
Test the pipeline against a file of real addresses before it touches production. A small test harness catches the cases the manual doesn't list.
- Create a test file. Save the function above as
validate.php, and add a line that reads a text file of one address per line. - Build a sample. Include 20 to 30 addresses from your real data: plus-tagged addresses, a few known typos, role addresses like
info@, and some addresses with trailing spaces. - Run it from the command line. Use
php -ror a small loop, and print each address with its result. - Read the failures by category. Rejections that are syntax errors need a code fix. Rejections on live domains are usually DNS or resolver issues, so check your server's DNS before blaming the data.
- Repeat from your production host. Outbound DNS and SMTP rules differ between shared hosting, containers and cloud VMs. Test from the environment that will run the code.
Bottom line: A 30-address test on production infrastructure tells you more than any published example.
Why isn't filter_var enough for a real validation system?
filter_var plus DNS catches malformed input and dead domains. It misses the problems that hurt senders most: addresses that exist but shouldn't be mailed.
The gaps fall into four groups:
- Non-existent mailboxes on live domains.
old.employee@yourcompany.commay have a working MX record while the mailbox was deleted years ago. Only a mailbox-level check can see that. - Catch-all domains. Some servers accept every recipient during the SMTP conversation and sort out real mailboxes later. A "yes" from such a server tells you nothing about the individual, so many verifiers flag these as Risky.
- Disposable and role-based addresses.
filter_vartreats disposable-domain addresses andinfo@mailboxes as ordinary. Disposable domains are commonly used to get around signup controls, and role mailboxes often reach several people or none. - Consent and engagement. No technical check can prove someone wants your email. That's a process question, covered in our guide to email list maintenance best practices.
The compliance stakes are real. Google asks bulk senders to keep user-reported spam below 0.10% and never reach 0.30% (Gmail sender guidelines). Invalid and abandoned addresses feed spam traps and complaints. The syntax check you add today is the cheapest layer of the broader email verification compliance and hygiene defence you'll need later.
Bottom line: A PHP pipeline can tell you an address is well-formed and its domain exists. It can't tell you the mailbox is live or the person agreed to hear from you.
Which validation layer should you use?
Use each layer for what it proves. The table compares them side by side.
| Layer | What it proves | What it cannot prove | Cost and latency | Where it runs |
|---|---|---|---|---|
filter_var (FILTER_VALIDATE_EMAIL) |
The string follows the accepted address pattern | Domain or mailbox existence | No network; negligible | Your PHP code |
| DNS MX / A check | The domain can receive mail | Whether a specific mailbox exists | One DNS query per domain, cacheable | Your PHP code |
| SMTP mailbox check | The receiving server accepted the recipient at that moment | Consent, engagement, or catch-all ambiguity | A live network conversation; often blocked on some hosts | Your server or a verification service |
| Verification service (bulk or API) | Valid, Risky or Invalid status, plus catch-all, disposable and role flags | Opt-in or intent | Upload or API call; per-plan quotas | Vendor infrastructure |
If you want a library rather than hand-written code, the egulias/email-validator package offers separate validation classes, including RFC-based, DNS-based and spoofing checks. Its README describes the options for each version, so check that before wiring it in. It still stops at the domain and server level, so it doesn't replace a mailbox-level verifier for lists.
The right combination depends on the job:
| Situation | Recommended approach |
|---|---|
| Signup form, one address at a time | filter_var plus cached MX/A check; decide the timeout policy in advance |
| Checkout or login | filter_var only; keep it shallow and fast |
| Importing or cleaning a list of 5,000+ rows | Export CSV, verify the whole file, re-import Valid rows only |
| Ongoing checks on new signups | Batch new addresses through the verification API on a schedule |
Keep the browser check as a convenience only. A JavaScript check improves the experience, but the server must validate again because anyone can bypass the browser. Our client-side vs server-side email validation comparison and the JavaScript validation guide explain the split.
Bottom line: Use filter_var for shape, DNS for domain health, and a verification service for mailbox-level decisions on lists.
How do you verify a large list from PHP with Unlimited Verifier?
Verification services suit whole lists because they combine mailbox-level checks with flags a PHP script can't produce. Unlimited Verifier checks syntax, domain, MX records and the SMTP mailbox, detects catch-all domains, flags disposable and role-based addresses, and sorts results into Valid, Risky or Invalid. Among the best email verification tools, weigh it against your volume, data-handling needs and integration preferences.
Here is the workflow for a PHP-driven list:
- Export your contacts to CSV. This PDO snippet writes a single-column file:
$stmt = $pdo->query('SELECT email FROM contacts WHERE email IS NOT NULL');
$out = fopen('contacts-to-verify.csv', 'w');
fputcsv($out, ['email']);
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
fputcsv($out, [trim($row['email'])]);
}
fclose($out);
- Pre-filter with
filter_var. Remove malformed rows before uploading. Syntax failures are free to fix locally, and a smaller file processes faster. - Split the file to fit your plan. Pro lists hold up to 25,000 emails each. Free lists hold up to 150.
- Create an account. You can sign up for free. The Free plan is enough to test the pipeline on a 150-row sample before you commit.
- Upload the file. Use Upload and verify a list. CSV and Excel files up to 10MB are accepted, and the email column is detected automatically.
- Read the three buckets. Valid addresses are ready to use. Invalid addresses should be removed and suppressed. Risky addresses include catch-all domains, disposable addresses and role accounts. Hold these back, and check specific high-value ones with the free email checker. For how catch-all results are handled, see Catch-all email verification.
- Export the results as CSV, Excel or JSON. JSON is the easiest format for a PHP import script. Free keeps results for 24 hours and Pro for 30 days, so download promptly.
- Re-import Valid rows. Unlimited Verifier has no native ESP, CRM or Zapier integrations, so the import step is yours: a PHP script that updates a
statuscolumn, or your platform's CSV importer.
Bottom line: Pre-filter locally, split to the plan's list cap, verify, then import only the Valid rows back.
When should you call the API instead of uploading a file?
Call the API when addresses arrive one at a time or in a steady stream, such as signups and form submissions. Uploads suit one-off cleanups. Neither is better in general; the arrival pattern decides it.
Unlimited Verifier's REST API uses keys from the Email verification API page. It supports single-email checks and bulk batches of up to 10,000 emails per request. API access is part of the Pro plan, which includes 100,000 API emails a month. It is not available on Free. For workflow patterns, see email verification API and automation.
Plan your quota before you go live. A pipeline that checks every signup can use up a monthly allowance faster than you expect. For rate-limit behaviour and safe retries, read email validation API rate limits explained.
Bottom line: Use the API for streams and uploads for batches, and do the quota arithmetic before writing the integration.
What does cleaning a 46,860-row CRM export cost?
This scenario is illustrative. The row counts, outcomes and timing are hypothetical; the plan limits and prices are real.
Starting point: A B2B agency exports 48,000 contacts from a legacy CRM for a prospecting campaign. Its approach resembles the process in email verification for sales prospecting.
Step 1: Local pre-filter. A filter_var pass removes 1,140 malformed rows, leaving 46,860 contacts (48,000 − 1,140).
Step 2: Split to the Pro cap. The 25,000-row limit per list gives two files:
25,000 + 21,860 = 46,860
Step 3: Budget the deep verifications. Pro includes 25,000 deep verifications a month, and standard verification is unlimited on every plan. The agency sends its riskiest 25,000 contacts (the oldest and imported ones) through deep verification. The other 21,860 still receive standard verification, but they don't draw on the deep quota. Covering all 46,860 deeply would take two monthly quota cycles, since 46,860 exceeds 25,000.
Step 4: Illustrative results.
| Bucket | Count | Share of 46,860 |
|---|---|---|
| Valid | 39,500 | 84.3% |
| Risky | 4,100 | 8.7% |
| Invalid | 3,260 | 7.0% |
Check the arithmetic: 39,500 + 4,100 + 3,260 = 46,860.
Step 5: Cost. Pro costs $29 a month, or $25 a month billed annually. If the agency uses the full 25,000 deep quota in one month, the monthly plan works out to about $1.16 per 1,000 deep checks ($29 ÷ 25). On annual billing it's $1.00 per 1,000. Compare pricing at your real volume rather than at list price, which is the approach in our email verification pricing overview.
Step 6: Import and suppress. The 39,500 Valid contacts go back to the CRM as the sending audience. The 3,260 Invalid addresses are suppressed permanently. The 4,100 Risky addresses stay out of general campaigns until a small test send shows they're safe.
Ongoing check. Suppose new signups arrive at roughly 3,000 a day. Over 30 days that's 3,000 × 30 = 90,000 addresses, which fits within Pro's 100,000 API emails with 10,000 to spare. If volume grows, budget for the next tier before you hit the cap.
Bottom line: The arithmetic decides the plan. List caps set the file count, the deep quota sets the scope, and monthly API volume sets the ongoing cost.
What are the most common mistakes with PHP email validation?
These pitfalls appear often in public discussions of PHP validation code, and most of them are easy to avoid once you know them.
- Treating a
filter_varpass as a deliverable address. It's a syntax result. Mailbox and domain-health checks are separate. - Rejecting timeouts as invalid. A resolver outage then becomes a customer-facing signup failure. Log it and re-check later.
- Checking only MX records. Some domains receive mail through the A-record fallback, so an MX-only check can reject working addresses.
- Forgetting
trim(). Hidden spaces from copied data fail the check and look like user typos. - Stripping plus-addressing.
jane+news@example.comis valid. Removing the tag changes the address and can merge two subscribers. - Copying a regex from a forum post. Hand-written patterns usually reject valid addresses or accept invalid ones. Use the built-in filter or a maintained library.
- Running SMTP checks from a host that blocks port 25. Every check then fails, and the failures look like invalid addresses. Confirm connectivity first, and see why SMTP email verification gets blocked.
- Validating only in the browser. Any direct HTTP request bypasses client-side checks.
- Verifying once and never again. Addresses decay as people change jobs. Schedule re-verification, and cover signup flows as described in how to add real-time email verification to signup forms.
- Losing suppression history during import. Export and keep your bounce and unsubscribe lists before any re-import, so you don't mail people you already removed. Fixing the source of bad addresses matters too, so review email list growth strategies to keep new junk from entering at the signup stage.
Bottom line: Most failures come from confusing syntax, domain health and mailbox status, or from letting infrastructure problems pass for bad data.
How we compared (and limitations)
This article is based on public documentation: the PHP filter and DNS function manuals, RFC 3696, RFC 5321, Google's sender guidelines and the egulias/email-validator README. We haven't benchmarked filter_var against a reference set of addresses, and we haven't measured DNS or SMTP behaviour across hosting environments. Behaviour can differ between PHP versions, so confirm details against the manual for the version you run.
Unlimited Verifier details come from its published plan information. The company states 99.5% accuracy for deep verification. Treat that as the company's own figure, not an independent benchmark. The worked example uses hypothetical counts; its percentages and costs are arithmetic on those counts. Verification services change rules and quotas over time, so check current plan details before planning a large project.
Bottom line: Use the published limits as a starting point, then measure against your own list before you commit.
Syntax check vs. deliverability on sample inputs
| Input | filter_var result | Deliverable? |
|---|---|---|
| jane.doe+news@example.com | Pass | Depends on mailbox |
| ' jane@example.com' (leading space) | Fail unless trimmed | Trim first |
| jane@gmial.com | Pass | Unknown: typo domain may be parked |
| jane@localhost | Fail or unreliable | No public MX |
Frequently asked questions
Does filter_var check if an email exists?
No. filter_var with FILTER_VALIDATE_EMAIL only tests whether the string matches email syntax. It never contacts a mail server or checks whether the mailbox exists. To learn more about deliverability, you need a DNS lookup and a mailbox-level verification step.
Should I use a regex instead of filter_var?
Usually not. filter_var is built into PHP, needs no package, and is maintained with the language. Custom regexes are easy to get wrong and often reject valid addresses. Use filter_var for the format gate and add separate checks for deliverability.
How do I check if an email domain has MX records in PHP?
Use checkdnsrr($domain, 'MX') to test for MX records. If none exist, you can fall back to checking for an A record, as RFC 5321 describes. Treat DNS timeouts as inconclusive rather than invalid so temporary resolver issues don't reject good addresses.
Does filter_var accept addresses with plus signs?
Yes. Plus addressing such as jane.doe+news@example.com is syntactically valid and passes FILTER_VALIDATE_EMAIL. Whether the plus address is deliverable depends on the mailbox provider, which the filter cannot see.
Why does filter_var accept jane@gmial.com?
The address is well-formed, so the syntax check passes. Whether it reaches anyone depends on whether someone registered that domain and runs mail servers. A DNS check may help, but a parked typo domain can still have records, so it will not catch every typo.
Should I trim whitespace before calling filter_var?
Yes. Addresses copied from spreadsheets, PDFs, or emails often include leading or trailing spaces. Call trim() first so a valid address is not rejected for stray characters, and so you store a clean value.
Can filter_var validate Unicode email addresses?
Only with the FILTER_FLAG_EMAIL_UNICODE flag, which arrived in PHP 7.1. Check the PHP filter manual for your version, since behaviour and supported syntax can differ between releases.
How should I validate a large CSV list of emails in PHP?
Run filter_var and DNS checks for a quick pass, but use a dedicated verification service for deliverability at scale. Export the list, verify it, and re-import only the rows marked valid. Keep a copy of the original file so you can audit rejections.
Cut Bounces and Protect Your Sender Reputation With Unlimited Email Verification
Every invalid address you send to hurts your sender reputation and your inbox placement. Verifying your list before each send means fewer bounces, healthier deliverability, and a predictable cost. With Unlimited Verifier, standard verification is unlimited on every plan, with no per-email fees.
Unlimited Verifier checks syntax, domain, MX records and the SMTP mailbox. It also detects catch-all domains and flags disposable and role-based addresses. Export a CSV from your email platform or CRM, upload and verify the list, then re-import the clean results. You can also automate checks with the email verification API.
| Free | Pro | |
|---|---|---|
| Price | $0 | $29/month ($25/month billed annually) |
| Lists | 25 a month, up to 150 emails each | Unlimited, up to 25,000 emails each |
| Deep verifications | 750 a month | 25,000 a month |
| API access | No | Yes (100,000 emails a month) |
| Result retention | 24 hours | 30 days |
Why teams choose Unlimited Verifier
- Unlimited standard verification on all plans, including Free, with no per-email fees.
- Catch-all detection so you know which domains accept every address.
- Clear Valid / Risky / Invalid results, exportable as CSV, Excel or JSON.
- An open-source verification engine you can inspect on GitHub.
Unlimited Verifier states 99.5% accuracy for deep verification.
Create a free account and verify your next list before you hit send.
Want to test a single address first? Try the free email checker.