<?php
function validateEmailFormat(string $email): bool {
// PHP 內建過濾器 (PHP 5.2+)
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
return false;
}
// 額外長度限制 (RFC 5321: local-part 64, domain 255, total 254)
if (strlen($email) > 254) return false;
$parts = explode('@', $email);
if (strlen($parts[0]) > 64) return false;
return true;
}
// 更嚴格正則 (可選)
$strictRegex = '/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$/';
<?php
function checkDnsMx(string $domain): bool {
// Windows 相容:checkdnsrr 在舊版 PHP 不支援
if (function_exists('checkdnsrr')) {
return checkdnsrr($domain, 'MX');
}
// 替代:nslookup (較慢、依賴系統工具)
$output = [];
exec("nslookup -type=MX " . escapeshellarg($domain), $output, $returnVar);
return $returnVar === 0 && preg_match('/mail exchanger/', implode("\n", $output));
}
// 完整驗證函數
function validateEmail(string $email): array {
$result = ['valid' => false, 'reason' => ''];
if (!validateEmailFormat($email)) {
$result['reason'] = 'format_invalid';
return $result;
}
$domain = substr(strrchr($email, '@'), 1);
if (!checkDnsMx($domain)) {
$result['reason'] = 'no_mx_record';
return $result;
}
$result['valid'] = true;
$result['domain'] = $domain;
return $result;
}
// 測試
var_dump(validateEmail('test@gmail.com')); // true
var_dump(validateEmail('fake@nonexist123.xyz')); // false, no_mx_record
var_dump(validateEmail('invalid-email')); // false, format_invalid
function smtpCheck(string $email, string $from = 'verify@example.com'): bool {
$domain = substr(strrchr($email, '@'), 1);
$mxHosts = [];
if (!dns_get_mx($domain, $mxHosts)) return false;
foreach ($mxHosts as $mx) {
$host = $mx['host'];
$port = 25;
$timeout = 5;
$fp = @fsockopen($host, $port, $errno, $errstr, $timeout);
if (!$fp) continue;
stream_set_timeout($fp, $timeout);
$read = fgets($fp, 1024); // 220 banner
if (!str_starts_with($read, '220')) { fclose($fp); continue; }
fwrite($fp, "HELO " . gethostname() . "\r\n");
if (!preg_match('/^250/', fgets($fp, 1024))) { fclose($fp); continue; }
fwrite($fp, "MAIL FROM:<$from>\r\n");
if (!preg_match('/^250/', fgets($fp, 1024))) { fclose($fp); continue; }
fwrite($fp, "RCPT TO:<$email>\r\n");
$response = fgets($fp, 1024);
fwrite($fp, "QUIT\r\n");
fclose($fp);
// 250 = 存在, 550/551/553 = 不存在, 450/451/452 = 暫時錯誤
return str_starts_with($response, '250');
}
return false;
}
警告:頻繁 SMTP 驗證會導致 IP 被列入黑名單,建議僅在註冊時單次驗證,並配合郵件發送驗證碼雙重確認。
$disposableDomains = [
'mailinator.com', '10minutemail.com', 'guerrillamail.com',
'tempmail.com', 'throwawaymail.com', 'yopmail.com',
// 定期更新列表或使用 API (如 kickbox.io, hunter.io)
];
function isDisposable(string $email): bool {
global $disposableDomains;
$domain = strtolower(substr(strrchr($email, '@'), 1));
return in_array($domain, $disposableDomains, true);
}
type="email" + JS 正則)