PHP邮箱验证无法识别.com.com无效后缀问题求助
Fixing the Invalid .com.com Email Validation Issue in PHP
Hey there! Let's tackle that email validation problem where addresses like user@domain.com.com are incorrectly marked as valid. Your current code has a few key issues we can address to make the validation robust:
What's Wrong with the Original Code?
- Deprecated Function:
eregi()has been deprecated since PHP 5.3 and removed entirely in PHP 7.0. We should switch topreg_match(), the modern, supported regex function for PHP. - Weak Regular Expression: The original regex doesn't properly restrict the top-level domain (TLD) format, allowing repeated invalid suffixes like
.com.comto slip through. - Unsafe Domain Extraction: Using
array_pop(explode("@", $email))can fail if the email has multiple@characters (which is invalid anyway, but we should handle this edge case cleanly).
Updated, Robust Validation Code
Here's the revised version of your code with fixes for all these issues:
<?php if(isset($_POST['submit'])) { function validate_email($email) { // First, use PHP's built-in email filter for reliable basic validation if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { return 0; } // Extract the domain part safely (ensure exactly one @ exists) $emailParts = explode("@", $email); if (count($emailParts) !== 2) { return 0; } $domain = end($emailParts); // Strict regex to block invalid TLDs like .com.com $domainRegex = '/^([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,63}$/'; if (!preg_match($domainRegex, $domain)) { return 0; } // Optional: Verify domain has valid MX records (adds extra legitimacy check) return checkdnsrr($domain, "MX") ? 1 : 0; } $email = $_POST['email']; echo validate_email($email); } ?> <form action="" method="post"> <h1>Email</h1> <input type="email" name="email"> <button type="submit" name="submit">SUBMIT</button> </form>
Key Improvements Explained
- Built-in Email Filter:
filter_var(FILTER_VALIDATE_EMAIL)handles core email structure checks (proper@placement, valid local part characters) using a well-tested, standardized regex—no need to reinvent the wheel here. - Strict Domain Regex: The domain regex ensures the final TLD is between 2-63 characters (matching DNS standards) and blocks nested invalid suffixes like
.com.com. - Safe Domain Extraction: We first confirm there's exactly one
@before extracting the domain, avoiding messy edge cases with malformed emails. - Modern Regex Support:
preg_match()replaces the deprecatederegi(), ensuring compatibility with all supported PHP versions.
Testing the Fix
- Valid emails like
john.doe@example.comwill return1(assuming the domain has valid MX records). - Invalid emails like
jane@test.com.comwill return0immediately, thanks to the strict domain regex check.
内容的提问来源于stack exchange,提问作者HILU RAJU
相关产品推荐
相关产品推荐

