Skip to content

PHP email validation: filter_var, MX checks and a verification API call with curl

· 7 min read · Tutorials

PHP email validation works best in three steps: filter_var($email, FILTER_VALIDATE_EMAIL) to check the format, checkdnsrr() to confirm the domain can receive mail, and a call to a verification API (here with PHP's curl extension) for what neither can know: typos of big providers, disposable inboxes, and whether the mailbox actually exists. Each step is cheap to add, and each catches things the previous one lets through. All code below is plain PHP 8, no framework.

If you're on Laravel, the Laravel validation rule for disposable emails wraps the API step in a ValidationRule. This post is the framework-free version.

Step 1: check the format with filter_var

PHP ships an email validator. Use it instead of a regex from Stack Overflow:

<?php
function isValidEmailFormat(string $email): bool
{
    $email = trim($email);
    if ($email === '' || strlen($email) > 254) {
        return false;
    }
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

var_dump(isValidEmailFormat('jane@example.com'));   // bool(true)
var_dump(isValidEmailFormat('jane@@example.com'));  // bool(false)
var_dump(isValidEmailFormat('jane example.com'));   // bool(false)

filter_var returns the filtered string on success and false on failure, so compare with !== false. A few things to know about it, from the PHP manual's validation filters page:

  • It validates against the RFC 822 addr-spec syntax, with documented exceptions: comments, whitespace folding and dotless domain names (jane@localhost) are not supported. Some addresses it allows are rare in practice; that's fine, the next steps catch dead ones.
  • Non-ASCII local parts are rejected by default. Pass FILTER_FLAG_EMAIL_UNICODE (PHP 7.1+) to allow them: filter_var($email, FILTER_VALIDATE_EMAIL, FILTER_FLAG_EMAIL_UNICODE).
  • Internationalized domains (bücher.de) need converting first. Convert the domain to punycode with idn_to_ascii() from the intl extension, then validate.

Here's a version that handles both:

<?php
/** Returns the normalized address (punycode domain, lowercased domain) or null. */
function normalizeEmail(string $input): ?string
{
    $email = trim($input);
    $at = strrpos($email, '@');
    if ($at === false || $at === 0 || $at === strlen($email) - 1) {
        return null;
    }
    $local = substr($email, 0, $at);
    $domain = mb_strtolower(substr($email, $at + 1));

    if (function_exists('idn_to_ascii') && preg_match('/[^\x20-\x7e]/', $domain)) {
        $ascii = idn_to_ascii($domain, IDNA_DEFAULT, INTL_IDNA_VARIANT_UTS46);
        if ($ascii === false) {
            return null;
        }
        $domain = $ascii;
    }

    $normalized = $local . '@' . $domain;
    if (strlen($normalized) > 254) {
        return null;
    }
    $ok = filter_var($normalized, FILTER_VALIDATE_EMAIL, FILTER_FLAG_EMAIL_UNICODE);
    return $ok === false ? null : $normalized;
}

The domain is lowercased; the local part is left alone, because some servers treat it as case-sensitive (almost none do in practice, but you don't gain anything by changing it).

Step 2: check the domain can receive mail

A valid format with a domain that doesn't exist is still a dead address. checkdnsrr() and getmxrr() query DNS from PHP:

<?php
function domainAcceptsMail(string $domain): bool
{
    $domain = rtrim($domain, '.') . '.'; // trailing dot: don't let the resolver append a search domain
    if (getmxrr($domain, $hosts)) {
        // A "null MX" (a single MX of ".") means the domain explicitly refuses mail (RFC 7505).
        return !(count($hosts) === 1 && ($hosts[0] === '' || $hosts[0] === '.'));
    }
    // No MX: SMTP falls back to the domain's own address record (RFC 5321, section 5.1).
    return checkdnsrr($domain, 'A') || checkdnsrr($domain, 'AAAA');
}

$email = normalizeEmail('jane@example.com');
$domain = substr($email, strrpos($email, '@') + 1);
var_dump(domainAcceptsMail($domain));

What this catches: typo domains that don't exist, made-up domains, companies that shut down and let the domain lapse. What it costs: a DNS query, usually milliseconds, sometimes seconds if a resolver is slow. Cache the result per domain (APCu, Redis, or your framework cache) for a few hours so repeat signups from the same domain don't hit DNS again.

The A/AAAA fallback is what RFC 5321 specifies, but in practice a domain with only a website and no MX often doesn't accept mail. Checking MX records for an email domain covers that judgement call and the edge cases.

What the built-in functions can't tell you

After steps 1 and 2 you know the address is well-formed and the domain has somewhere to send mail. Still unknown:

Question Why PHP alone can't answer
Is gmial.com a typo of gmail.com? The typo domain may exist and even have MX records
Is the domain a disposable inbox? Needs a maintained list of several thousand domains
Is the local part machine-generated? Needs a scoring model, not a pattern
Does the mailbox exist? Needs an SMTP RCPT TO conversation on port 25
Is the domain catch-all? Needs a second SMTP probe with an address that can't exist

You could run the SMTP check from PHP with fsockopen() on port 25. In practice most hosting and cloud providers block outbound port 25, and when it works your server's IP needs a good reputation or the receiving server will refuse or lie. SMTP email verification limits explains why this is hard to do well yourself.

Step 3: call a verification API with curl

pingutil runs the mailbox check from dedicated prober infrastructure, along with the disposable list, typo suggestions and catch-all detection. The PHP side is a curl POST.

<?php
final class PingutilClient
{
    public function __construct(
        private string $apiKey,
        private string $base = 'https://pingutil.com',
    ) {}

    /** Full mailbox verification. Returns the decoded response, or null on failure. */
    public function verify(string $email, int $timeout = 30): ?array
    {
        return $this->post('/v1/verify', ['email' => $email], $timeout);
    }

    /** Fast domain category + spam verdict, no mailbox check. */
    public function quickLookup(string $email, int $timeout = 3): ?array
    {
        return $this->post('/v1/lookup', ['input' => $email, 'skip_enrichment' => true], $timeout);
    }

    private function post(string $path, array $body, int $timeout): ?array
    {
        $ch = curl_init($this->base . $path);
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode($body, JSON_THROW_ON_ERROR),
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . $this->apiKey,
                'Content-Type: application/json',
                'Accept: application/json',
            ],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CONNECTTIMEOUT => 5,
            CURLOPT_TIMEOUT => $timeout,
        ]);
        $raw = curl_exec($ch);
        $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
        $err = curl_error($ch);

        if ($raw === false) {
            error_log("pingutil $path failed: $err");
            return null;
        }
        $data = json_decode($raw, true);
        if ($status !== 200 || !is_array($data)) {
            error_log("pingutil $path HTTP $status: " . ($data['error'] ?? substr((string) $raw, 0, 200)));
            return null;
        }
        return $data;
    }
}

The fields you'll use from /v1/verify:

  • status: valid, invalid, risky or unknown.
  • reason: why, for example mailbox_not_found, no_mx, disposable_domain, accept_all, role_based, greylisted.
  • did_you_mean: the corrected address when the domain looks like a typo of a major provider, otherwise null.
  • score: 0 to 100, how likely a message would reach a person.
  • checks: the facts behind the decision (disposable, free_provider, role_based, has_mx, mailbox, catch_all…).

From /v1/lookup: category (free, disposable, company, educational, government, isp), verdict.is_spam, verdict.low_trust and verdict.reason. Email verification statuses explained goes through each status in detail.

Putting it together in a signup handler

<?php
// signup.php
require __DIR__ . '/email.php'; // normalizeEmail(), domainAcceptsMail(), PingutilClient

header('Content-Type: application/json');

$input = json_decode(file_get_contents('php://input'), true) ?? [];
$email = normalizeEmail((string) ($input['email'] ?? ''));

if ($email === null) {
    http_response_code(422);
    echo json_encode(['error' => 'Enter a valid email address.']);
    exit;
}

$domain = substr($email, strrpos($email, '@') + 1);
if (!domainAcceptsMail($domain)) {
    http_response_code(422);
    echo json_encode(['error' => "The domain $domain can't receive email. Please check the address."]);
    exit;
}

$client = new PingutilClient(getenv('PINGUTIL_KEY'));
$result = $client->verify($email);

if ($result !== null && $result['status'] === 'invalid') {
    http_response_code(422);
    $msg = $result['did_you_mean']
        ? "Did you mean {$result['did_you_mean']}?"
        : ($result['reason'] === 'disposable_domain'
            ? 'Please use a permanent email address.'
            : "We couldn't deliver to this address. Please check it.");
    echo json_encode(['error' => $msg, 'suggestion' => $result['did_you_mean']]);
    exit;
}

// valid, risky, unknown, or the API was unreachable: accept and send a confirmation link.
// Store the status so you can review risky accounts later.
$status = $result['status'] ?? 'unchecked';
// createUser($email, $status); sendConfirmation($email);

echo json_encode(['ok' => true, 'email_status' => $status]);

Decisions baked in here, and why:

  • Reject only on invalid. risky covers catch-all domains (very common for companies) and role addresses; unknown means the mail server didn't give a straight answer. Neither means the address is bad.
  • Fail open. If the API call times out or errors, $result is null and the signup continues. The confirmation email is still the final check.
  • Don't auto-correct. did_you_mean goes back to the form as a suggestion. The user confirms it.
  • DNS check runs first. It's cheap and local, so obvious dead domains never cost an API call.

If verification latency matters for your form (a mailbox check can take seconds on a slow server), use quickLookup() inline to block disposable and machine-generated addresses, and run verify() from a queue worker right after the account is created.

Checklist for PHP email validation

  1. trim() the input and cap length at 254.
  2. Convert IDN domains with idn_to_ascii(), then filter_var(..., FILTER_VALIDATE_EMAIL, FILTER_FLAG_EMAIL_UNICODE).
  3. getmxrr(), with A/AAAA fallback and null-MX handling. Cache per domain.
  4. Call the verification API with short connect and total timeouts.
  5. Reject invalid, suggest did_you_mean, accept the rest and confirm by email.
  6. Keep the API key in an environment variable, never in code or the browser.

The API reference lists every request flag and response field. If you're wiring this into a larger system, the email verification API integration guide covers retries, caching and budgets.

Questions people ask

Is filter_var FILTER_VALIDATE_EMAIL enough to validate an email in PHP?
It's enough to check the format, and it's better than writing your own regex. It can't tell you whether the domain receives mail, whether the address is a typo of a big provider, or whether it's a disposable inbox. Those need DNS or an API call.
How do I check if an email domain has MX records in PHP?
Call checkdnsrr($domain, 'MX'), which returns true if at least one MX record exists, or getmxrr() to get the hostnames. If there's no MX, check for an A or AAAA record too, because mail servers fall back to the domain's address record when no MX is published.
Can PHP check whether a mailbox exists without sending an email?
In principle, by opening an SMTP connection to port 25 and issuing RCPT TO, but most hosting providers block outbound port 25 and many mail servers don't answer truthfully. Calling a verification API that runs the SMTP check from dedicated infrastructure is the practical option.