Validate Email Address Php [updated] May 2026
While filter_var() is preferred, regex can be useful for custom rules:
Many servers block this technique, and it can be flagged as abuse. 6. Complete Production-Ready Function /** * Comprehensive email validation * * @param string $email Email to validate * @param bool $checkDNS Whether to check MX records * @return array ['valid' => bool, 'message' => string] */ function validateEmailAdvanced($email, $checkDNS = false) // Trim whitespace $email = trim($email); // Empty check if (empty($email)) return ['valid' => false, 'message' => 'Email cannot be empty']; validate email address php
Email validation is a critical part of user input handling. PHP offers several methods, from simple checks to deep verification. 1. Basic Syntax Validation with filter_var() The simplest and most reliable method for basic validation is PHP's built-in filter_var() function with the FILTER_VALIDATE_EMAIL filter. While filter_var() is preferred, regex can be useful
function validateEmail($email) // Remove illegal characters $sanitized = filter_var($email, FILTER_SANITIZE_EMAIL); // Validate if (filter_var($sanitized, FILTER_VALIDATE_EMAIL)) return ["valid" => true, "email" => $sanitized]; PHP offers several methods, from simple checks to
This checks that the email follows RFC 822/RFC 2822 standards – correct format, presence of @ symbol, valid domain characters, etc. It does not check if the domain actually exists. 2. Domain Validation (DNS Check) To verify the domain has valid MX (mail exchange) records:
// Optional DNS check if ($checkDNS) $domain = substr(strrchr($email, "@"), 1); if (!checkdnsrr($domain, 'MX') && !checkdnsrr($domain, 'A')) return ['valid' => false, 'message' => 'Domain has no mail server'];
$email = "user@example.com"; $domain = substr(strrchr($email, "@"), 1); if (filter_var($email, FILTER_VALIDATE_EMAIL) && checkdnsrr($domain, "MX")) echo "Valid email and domain has mail server"; else echo "Invalid email or domain has no MX records";