Skip to content
MailVet
PHP guide

Email validation in PHP

PHP has email validation built in: filter_var with FILTER_VALIDATE_EMAIL checks the format, and checkdnsrr confirms the domain publishes mail servers. Together they stop most typos and fake domains. Neither can see whether the mailbox exists; that takes a verification API call.

Step 1: check the format with filter_var

filter_var() returns the address when it's valid and false when it isn't, so compare with === false. It doesn't trim, so trim first. Add FILTER_FLAG_EMAIL_UNICODE (PHP 7.1 and later) if you need to accept non-ASCII characters before the @.

PHP
<?php
$email = trim($_POST['email'] ?? '');

if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
    $errors['email'] = 'Enter a valid email address.';
}

var_dump(filter_var('dana.reyes@gmail.com', FILTER_VALIDATE_EMAIL));  // string(20) "dana.reyes@gmail.com"
var_dump(filter_var('dana reyes@gmail.com', FILTER_VALIDATE_EMAIL));  // bool(false)
var_dump(filter_var('dana..reyes@gmail.com', FILTER_VALIDATE_EMAIL)); // bool(false)

Step 2: check the domain with checkdnsrr or getmxrr

checkdnsrr($domain, 'MX') answers yes or no. getmxrr() also returns the hostnames, which lets you spot a null MX: a domain that has published that it accepts no mail. Neither function takes a timeout; both wait as long as the server's resolver does.

PHP
<?php
// Call after filter_var() has passed.
function domain_accepts_mail(string $email): bool
{
    $domain = substr(strrchr($email, '@'), 1);

    // Internationalised domains need their ASCII (punycode) form for DNS lookups
    if (function_exists('idn_to_ascii')) {
        $domain = idn_to_ascii($domain, IDNA_DEFAULT, INTL_IDNA_VARIANT_UTS46) ?: $domain;
    }

    if (getmxrr($domain, $hosts)) {
        // A single "." host is a null MX (RFC 7505): the domain takes no mail
        return $hosts !== ['.'] && $hosts !== [''];
    }

    // No MX record: senders fall back to the domain's A/AAAA record (RFC 5321)
    return checkdnsrr($domain, 'A') || checkdnsrr($domain, 'AAAA');
}

// The one-line version, if a yes/no on MX is all you need:
$hasMx = checkdnsrr('gmail.com', 'MX'); // true

What filter_var and checkdnsrr can't tell you

Format and DNS checks pass plenty of addresses that will bounce. If you're on Laravel, the email:rfc,dns validation rule runs equivalent checks and has the same blind spots:

  • Dead mailboxes. former.employee@company.com has perfect syntax and a domain with healthy MX records.
  • Catch-all domains. The domain accepts mail for every address, so even the mail server's answer doesn't tell you whether a person is there.
  • Disposable inboxes. Throwaway-email domains have working MX records by design.
  • Typos at real domains. jhon@company.com instead of john@company.com passes both checks.

Step 3: verify the mailbox with cURL

Set both a connect timeout and a total timeout, and treat any failure as "couldn't check", not "invalid". timeout=5 asks the API to reply within five seconds; checks that need longer come back as HTTP 202 with status set to pending.

PHP
<?php
function mailvet_verify(string $email, int $waitSeconds = 5): ?array
{
    $url = 'https://api.mailvet.app/v1/verify?' . http_build_query([
        'email'   => $email,
        'timeout' => $waitSeconds, // 3 to 15 seconds before the API answers "pending"
    ]);

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_HTTPHEADER     => ['Authorization: Bearer ' . getenv('MAILVET_KEY')],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CONNECTTIMEOUT => 3,
        CURLOPT_TIMEOUT        => $waitSeconds + 3,
    ]);
    $body = curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);

    if ($body === false) {
        error_log('MailVet request failed: ' . curl_error($ch));
        return null; // timeout or network error
    }
    if ($status !== 200 && $status !== 202) {
        error_log("MailVet returned HTTP $status: $body");
        return null; // 401 bad key, 402 out of credits, 429 rate limited, 5xx
    }
    $data = json_decode($body, true);
    return is_array($data) ? $data : null; // null always means "couldn't check"
}

// In the form handler, after steps 1 and 2:
$check = mailvet_verify($email);

if (($check['status'] ?? null) === 'done'
    && ($check['result'] === 'undeliverable' || $check['reason'] === 'disposable')) {
    $errors['email'] = 'Please use a permanent address that can receive email.';
} else {
    // Accept: deliverable, risky (mailbox_full), unknown, pending, or not checked
    $emailStatus  = ($check['status'] ?? null) === 'pending' ? 'pending' : ($check['result'] ?? 'unchecked');
    $emailCheckId = $check['id'] ?? null;
}

Step 4: finish pending checks from a cron job

Store the verification id with the record and look it up later with GET /v1/verify/{id}. Run this every few minutes; slow checks usually finish within a few. If your app can receive webhooks, the verification.completed event delivers the same result without polling (see /docs/webhooks).

PHP (cron)
<?php
// cron/finish-email-checks.php: run every 5 minutes
$pdo = new PDO(getenv('DATABASE_DSN'), getenv('DATABASE_USER'), getenv('DATABASE_PASSWORD'), [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
$pending = $pdo->query(
    "SELECT id, email_check_id FROM users WHERE email_status = 'pending' LIMIT 500"
)->fetchAll(PDO::FETCH_ASSOC);
$update = $pdo->prepare('UPDATE users SET email_status = ?, email_reason = ? WHERE id = ?');

foreach ($pending as $row) {
    $ch = curl_init('https://api.mailvet.app/v1/verify/' . rawurlencode($row['email_check_id']));
    curl_setopt_array($ch, [
        CURLOPT_HTTPHEADER     => ['Authorization: Bearer ' . getenv('MAILVET_KEY')],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 10,
    ]);
    $body = curl_exec($ch);
    $v = $body === false ? null : json_decode($body, true);

    if (($v['status'] ?? null) === 'done') {
        $update->execute([$v['result'], $v['reason'], $row['id']]);
    }
    // Still pending, or the request failed: try again on the next run
}

What to accept on a PHP form

What came backExample reasonsOn a signup form
deliverableaccepted, catch_all_verifiedAccept
undeliverablemailbox_not_found, invalid_domainReject and ask the user to check for typos
riskydisposableReject, or allow with limits on free plans
riskymailbox_fullAccept and flag; your welcome email may not arrive yet
unknownno_response, catch_all_unresolvedAccept; no credit is used
HTTP 202, pendingNone yetAccept now; the cron job or webhook fills in the result
null from mailvet_verify()Timeout or errorAccept and log it
FAQ

PHP email validation questions

Is FILTER_VALIDATE_EMAIL good enough for email validation?

For format, yes: it follows the email RFCs closely enough for real-world forms. It doesn't check that the domain exists or that the mailbox is real, and it rejects non-ASCII characters before the @ unless you add FILTER_FLAG_EMAIL_UNICODE.

How do I check if an email domain exists in PHP?

Use checkdnsrr($domain, 'MX'), or getmxrr() if you also want the mail server hostnames. If there's no MX record, check for an A or AAAA record, which senders fall back to.

Why is checkdnsrr sometimes slow?

It waits on the server's DNS resolver and has no timeout parameter, so a slow or unreachable nameserver for the domain holds up the request until the resolver gives up. Cache results per domain, and tune resolver timeouts at the system level if it becomes a problem.

Can PHP check whether an email address exists over SMTP?

You can open a socket to the mail server with fsockopen() and ask about the recipient, but outbound port 25 is blocked on most hosting, catch-all domains accept every address, and repeated probes can get your server's IP blocklisted. A verification API handles that part.

Add the check filter_var can't do

One HTTPS request per address, catch-alls included, unknowns free. Start with 100 free credits.