Tutorials

PHP email validation: filter_var + domain check

PHP email validation has two jobs that people often fold into one: deciding whether a string is shaped like an address, and deciding whether mail to it has anywhere to go. This tutorial does the first with the built-in filter_var and the second with one cURL call to the LookValid email domain check, then turns the answer into a signup decision.

By LookValid engineering. Published 2026-11-06.

Layer one: check the syntax with filter_var

filter_var($email, FILTER_VALIDATE_EMAIL) returns the string when it passes and false when it does not. It checks the value against the addr-spec syntax in RFC 822, and it rejects comments, whitespace folding and dotless domain names such as user@localhost 1. If your users have non-ASCII characters before the @ sign, add FILTER_FLAG_EMAIL_UNICODE, which PHP has offered since 7.1.0 1.

The PHP manual is direct about the limit of this layer: email validation is complex, and the only true way to confirm that an address exists is to send mail to it 1. A syntactically perfect address can still sit on a domain that has no mail server, so the filter is the cheap first gate and not the whole answer.

Layer two: ask whether the domain can receive mail

The LookValid email domain check takes the address, reads the domain's public DNS and returns whether it publishes MX records, whether it is a known disposable provider, whether the local part is a role mailbox such as info@, and an overall deliverability_signal of good, risky or undeliverable. It never contacts the mailbox, so smtp_checked is always false. A found result costs 1 credit; an address the API cannot resolve comes back with found: false and costs nothing.

The request is one POST with a JSON body. In PHP the cURL extension needs a handful of options. CURLOPT_POSTFIELDS carries the body and CURLOPT_RETURNTRANSFER makes curl_exec() return the response as a string instead of printing it 23. Set CURLOPT_TIMEOUT as well: its default of 0 means a transfer never times out 2. curl_exec() returns false on a transport failure, so that case needs its own branch, separate from an HTTP error status 3.

The full function

A 429 status means the client sent too many requests, and the server says how long to wait in the Retry-After header, which holds either an HTTP-date or a number of seconds 45. Our API sends whole seconds. cURL hands each response header line to a CURLOPT_HEADERFUNCTION callback, which must return the number of bytes it handled 2, so the function below reads Retry-After there. The body is decoded with JSON_THROW_ON_ERROR, available since PHP 7.3, so a malformed response raises an exception instead of returning null 6.

<?php
declare(strict_types=1);
​
const LOOKVALID_API = 'https://YOUR_API_HOST';
​
function lookupDomain(string $email, int $maxAttempts = 4): array
{
    for ($attempt = 1; ; $attempt++) {
        $retryAfter = null;
        $ch = curl_init(LOOKVALID_API . '/v1/email-domain-check');
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode(['email' => $email], JSON_THROW_ON_ERROR),
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . getenv('LOOKVALID_API_KEY'),
                'Content-Type: application/json',
            ],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CONNECTTIMEOUT => 5,
            CURLOPT_TIMEOUT => 10,
            CURLOPT_HEADERFUNCTION => function ($handle, string $line) use (&$retryAfter): int {
                if (stripos($line, 'retry-after:') === 0) {
                    $retryAfter = (int) trim(substr($line, 12));
                }
                return strlen($line);
            },
        ]);
        $raw = curl_exec($ch);
        $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
​
        if ($raw === false) {
            if ($attempt >= $maxAttempts) {
                throw new RuntimeException('network error: ' . curl_error($ch));
            }
            sleep(2 ** $attempt);
            continue;
        }
        if ($status === 429 && $attempt < $maxAttempts) {
            sleep(max(1, $retryAfter ?? 1));
            continue;
        }
​
        $body = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
        if ($status !== 200) {
            $err = $body['error'] ?? [];
            if (($err['retryable'] ?? false) && $attempt < $maxAttempts) {
                sleep(2 ** $attempt);
                continue;
            }
            throw new RuntimeException(($err['code'] ?? 'error') . ': ' . ($err['message'] ?? 'request failed'));
        }
        return $body;
    }
}
​
function checkSignupEmail(string $email): array
{
    $email = trim($email);
    if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
        return ['allow' => false, 'why' => 'not shaped like an email address'];
    }
    $result = lookupDomain($email);
    if (!$result['found']) {
        return ['allow' => false, 'why' => $result['reason']];
    }
    $d = $result['data'];
    if ($d['disposable']) {
        return ['allow' => false, 'why' => 'disposable domain'];
    }
    if ($d['deliverability_signal'] === 'undeliverable') {
        return ['allow' => false, 'why' => 'domain accepts no mail'];
    }
    return ['allow' => true, 'review' => $d['deliverability_signal'] === 'risky'];
}
​
print_r(checkSignupEmail('new.user@example.org'));

Validate syntax, check the domain, retry on 429

Run it with LOOKVALID_API_KEY exported. The sample address uses example.org, which publishes a null MX record to say it takes no mail, so the check returns undeliverable and the function answers allow false with the reason "domain accepts no mail".

Turn the signal into a decision

Treat the three outcomes differently. found: false and undeliverable are safe to refuse, because the domain cannot receive mail. A disposable domain is a policy choice, and most signup forms refuse it. risky covers addresses that can receive mail but deserve a second look, such as a role mailbox, so the function lets them through and flags them for review.

What each result means for a signup form
ResultWhat it tells youUsual action
filter_var returns falseThe string is not an addressAsk the person to retype it; no API call is made
found falseThe domain does not exist in DNSAsk for another address; nothing is charged
deliverability_signal undeliverableNo MX, no address record, or a null MXRefuse the address
disposable trueA known throwaway providerRefuse or limit the account
deliverability_signal riskyA role mailbox such as info@, or a domain with no MX but an address recordAccept and mark for review
deliverability_signal goodMX records present and no risk check matchedAccept; the mailbox itself was not checked

What each result means for a signup form

Only a confirmation email proves a mailbox is real and read by the person who typed it. The domain check removes the addresses that could never work, so your confirmation emails go to fewer dead ends. For the same flow in another language see verify email domains in Node.js, and for what separates a valid address from a deliverable one see what makes an email address valid.

Run it

  1. Check that PHP 8 has the cURL extension: php -m lists curl.
  2. Export LOOKVALID_API_KEY in your shell, then save the code as check.php.
  3. Run php check.php and read the allow and why keys.

Read the email domain check product page for every response field, try an address in the email domain checker without a key, or begin with the quickstart.

Sources

  1. PHP manual: Validation Filters (FILTER_VALIDATE_EMAIL), read 2026-11-05
  2. PHP manual: cURL predefined constants, read 2026-11-05
  3. PHP manual: curl_exec, read 2026-11-05
  4. RFC 9110: HTTP Semantics (section 10.2.3, Retry-After), read 2026-11-05
  5. RFC 6585: Additional HTTP Status Codes (section 4, 429 Too Many Requests), read 2026-11-05
  6. PHP manual: json_decode, read 2026-11-05