1. Format check with filter_var
$email = trim($_POST['email'] ?? '');
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
exit('Please enter a valid email address.');
}
2. Does the domain accept email?
$domain = substr(strrchr($email, '@'), 1);
if (!checkdnsrr($domain, 'MX') && !checkdnsrr($domain, 'A')) {
exit('This email domain does not exist.');
}
3. Check the mailbox with the API
function validate_email_api(string $email): array {
$ch = curl_init('https://api.emailvalidation.io/v1/info?email=' . urlencode($email));
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => ['apikey: ' . getenv('EMAILVALIDATION_API_KEY')],
]);
$body = curl_exec($ch);
curl_close($ch);
return json_decode($body, true) ?? [];
}
$result = validate_email_api($email);
if (($result['state'] ?? '') === 'undeliverable' || !empty($result['disposable'])) {
exit('Please use a valid, permanent email address.');
}
Laravel
$request->validate([
'email' => ['required', 'email:rfc,dns', function ($attribute, $value, $fail) {
$r = Http::withHeaders(['apikey' => config('services.emailvalidation.key')])
->timeout(10)
->get('https://api.emailvalidation.io/v1/info', ['email' => $value])
->json();
if (($r['state'] ?? null) === 'undeliverable' || ($r['disposable'] ?? false)) {
$fail('Please use a valid, permanent email address.');
}
}],
]);
If the API call times out, let the address through rather than blocking the sign-up.