萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 郵箱驗證:從基礎格式檢查到常用域名白名單過濾

驗證層級

  1. 格式合法性:符合 RFC 5322 语法。
  2. 域名存在性:MX 記錄解析成功。
  3. 郵箱真實性:發送驗證碼,用戶點擊/輸入驗證。
  4. 業務規則:限制常用域名、禁止臨時郵箱、防惡意註冊。

基礎格式驗證(推薦 filter_var)

function checkEmailFormat($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

業務規則驗證:常用域名白名單 + 敏感詞過濾

class UserInputValidator {
    // 常用郵箱後綴白名單(可從配置文件讀取)
    private $allowedSuffixes = array(
        '@gmail.com', '@yahoo.com', '@hotmail.com', '@outlook.com', '@live.com',
        '@qq.com', '@163.com', '@126.com', '@sina.com', '@sohu.com',
        '@139.com', '@189.cn', '@wo.cn', '@foxmail.com', '@icloud.com',
        // 根據業務擴展...
    );

    // 敏感詞黑名單(防腳本注入、iframe等)
    private $forbiddenWords = array('script', 'iframe', 'javascript:', 'onload', 'onerror');

    /**
     * 綜合檢查用戶輸入(郵箱/用戶名等)
     */
    public function checkUserInput($inputString) {
        $lower = strtolower($inputString);
        foreach ($this->forbiddenWords as $word) {
            if (strpos($lower, $word) !== false) {
                return false;
            }
        }
        return true;
    }

    /**
     * 郵箱驗證:格式 + 單一@ + 後綴白名單
     */
    public function checkEmail($emailString) {
        if (!$this->checkUserInput($emailString)) return false;

        if (strpos($emailString, '@') === false) return false;

        $parts = explode('@', $emailString);
        if (count($parts) != 2) return false; // 多個 @

        $suffix = '@' . $parts[1];
        if (!in_array(strtolower($suffix), $this->allowedSuffixes)) {
            return false; // 不在白名單中
        }

        // 可選:進一步格式驗證
        return $this->checkEmailFormat($emailString);
    }
}

// 使用
$validator = new UserInputValidator();
$emails = ['test@gmail.com', 'hacker@evil.com', 'test
						
copyright © 萬盛學電腦網 all rights reserved