# Email Validation API Code Samples in PHP

URL: https://email-validation.org/docs/code-samples/php/
Updated: 2026-11-26

> Documentation index: https://email-validation.org/llms.txt

Copy-paste PHP examples that validate one address, send the API key in the `Authorization` header, retry
`429` and `503` answers after `Retry-After` when the wait is at most 10 seconds (never `key_daily_cap`, which lasts
until the next UTC day), and report other errors with their code and request id. Each uses the free test address
`accepted@sandbox.email-validation.org`; replace it with a real address when you are ready. The same samples in other
languages: [all code samples](https://email-validation.org/docs/code-samples/).

Set your key first: `export EV_API_KEY="ev_live_…"`.

The samples call `https://api.email-validation.org`. For EU data residency, replace it with `https://api-eu.email-validation.org`, or pass the SDK's EU base URL constant;
there `/v1/validate` takes `POST` only ([EU data residency](https://email-validation.org/docs/eu-data-residency/)).

## With the official SDK

The [official PHP SDK](https://email-validation.org/docs/sdks/php/) does the retries, timeouts and error mapping
for you: one call validates an address and every failure arrives as a typed error. There are official SDKs for JavaScript/TypeScript, Python, Go, PHP, Ruby, C#, Rust and Swift; those for Java, Kotlin, Dart, Elixir, C and Perl are built and tested and coming soon to their package registries. The plain
HTTP samples further down call the API directly.

**PHP**

```php
<?php

require __DIR__ . '/vendor/autoload.php';

use EmailValidation\Client;
use EmailValidation\Exception\EmailValidationException;
use EmailValidation\Exception\InsufficientCreditsException;

$client = new Client(apiKey: (string) getenv('EV_API_KEY'));

try {
    $result = $client->validate('accepted@sandbox.email-validation.org');
    echo $result->status, ' ', $result->reason, ' ', $result->action, PHP_EOL; // valid accepted send
} catch (InsufficientCreditsException $e) {
    echo 'buy credits; nothing was charged', PHP_EOL;
} catch (EmailValidationException $e) {
    echo $e->errorCode, ' ', $e->requestId, PHP_EOL;
}
```

## Validate an address

**PHP**

```php
<?php
function validate_email(string $email, int $attempts = 3): array
{
    for ($attempt = 1; ; $attempt++) {
        $headers = [];
        $ch = curl_init('https://api.email-validation.org/v1/validate');
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 20,
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . getenv('EV_API_KEY'),
                'Content-Type: application/json',
            ],
            CURLOPT_POSTFIELDS => json_encode(['email' => $email]),
            CURLOPT_HEADERFUNCTION => function ($ch, $line) use (&$headers) {
                $parts = explode(':', $line, 2);
                if (count($parts) === 2) {
                    $headers[strtolower(trim($parts[0]))] = trim($parts[1]);
                }
                return strlen($line);
            },
        ]);
        $raw = curl_exec($ch);
        if ($raw === false) {
            throw new RuntimeException(curl_error($ch));
        }
        $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
        $body = json_decode($raw, true);
        if ($status === 200) {
            return $body;
        }
        // Never wait out a long Retry-After: key_daily_cap lasts until the next UTC day.
        $wait = max(1, (int) ($headers['retry-after'] ?? 1));
        $code = $body['error']['code'] ?? '';
        if (in_array($status, [429, 503], true) && $code !== 'key_daily_cap' && $wait <= 10 && $attempt < $attempts) {
            sleep($wait);
            continue;
        }
        throw new RuntimeException("{$body['error']['code']}: {$body['error']['message']} ({$body['error']['request_id']})");
    }
}

$result = validate_email('accepted@sandbox.email-validation.org');
echo "{$result['status']} {$result['reason']} {$result['action']}\n";
```

## Verify a webhook

**PHP**

```php
<?php
function verify_webhook(string $rawBody, array $headers, string $secret, int $tolerance = 300): array
{
    $id = $headers['webhook-id'] ?? '';
    $timestamp = $headers['webhook-timestamp'] ?? '';
    $signatures = $headers['webhook-signature'] ?? '';
    if ($id === '' || $timestamp === '' || $signatures === '') {
        throw new RuntimeException('Missing webhook headers');
    }
    if (!ctype_digit($timestamp) || abs(time() - (int) $timestamp) > $tolerance) {
        throw new RuntimeException('Timestamp outside tolerance');
    }
    $key = base64_decode(preg_replace('/^whsec_/', '', $secret), true);
    if ($key === false) {
        throw new RuntimeException('Invalid webhook secret');
    }
    $expected = base64_encode(hash_hmac('sha256', "$id.$timestamp.$rawBody", $key, true));
    foreach (explode(' ', $signatures) as $entry) {
        [$version, $sig] = array_pad(explode(',', $entry, 2), 2, '');
        if ($version === 'v1' && hash_equals($expected, $sig)) {
            return json_decode($rawBody, true, 512, JSON_THROW_ON_ERROR);
        }
    }
    throw new RuntimeException('No valid signature');
}

// Read the raw body before any framework parses it.
$event = verify_webhook(
    file_get_contents('php://input'),
    array_change_key_case(getallheaders(), CASE_LOWER),
    getenv('EV_WEBHOOK_SECRET'),
);
```

## Other calls

- Read the credit balance: samples in curl, JavaScript and Python ([all code samples](https://email-validation.org/docs/code-samples/#credits)).
- Create a bulk job: samples in curl, JavaScript and Python ([all code samples](https://email-validation.org/docs/code-samples/#bulk)).

## Notes

- Use `POST` with a JSON body; it keeps addresses out of URLs and logs.
- Set the HTTP timeout to about 20 seconds: a check may take up to 15 seconds (10 by default).
- A `200` answer with the status `unknown` is a normal, free result, not an error.
- Every endpoint, field and error: the [API reference](https://email-validation.org/docs/api-reference/).
