萬盛學電腦網

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

PHP 用戶名密碼驗證正則:字母開頭用戶名、字母數字組合密碼、郵箱格式

三大核心驗證函數

<?php
/**
 * 驗證郵箱格式
 */
function isEmail(string $email): bool {
    // RFC 5322 簡化版,覆蓋 99% 常見郵箱
    $pattern = '/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/';
    return (bool)preg_match($pattern, $email);
}

/**
 * 驗證用戶名:字母開頭,4-20位,允許字母數字下劃線點
 */
function isUsername(string $username): bool {
    // ^[a-zA-Z]           必須以字母開頭
    // [a-zA-Z0-9._]{3,19} 後續 3-19 位 (總長 4-20)
    // $                    結束
    $pattern = '/^[a-zA-Z][a-zA-Z0-9._]{3,19}$/';
    return (bool)preg_match($pattern, $username);
}

/**
 * 驗證密碼:4-20 位字母數字下劃線組合 (建議加強策略見下)
 */
function isPassword(string $password): bool {
    // \w = [a-zA-Z0-9_]
    $pattern = '/^\w{4,20}$/';
    return (bool)preg_match($pattern, $password);
}

// 測試
$tests = [
    ['user' => 'Tom_123', 'pass' => 'abc123', 'email' => 'tom@example.com'],
    ['user' => '123Tom',  'pass' => 'abc',     'email' => 'invalid'],
    ['user' => 'Jerry',   'pass' => 'pass1234', 'email' => 'jerry@test.cn'],
];

foreach ($tests as $t) {
    echo "User: {$t['user']} => " . (isUsername($t['user']) ? '✓' : '✗') . "\n";
    echo "Pass: {$t['pass']} => " . (isPassword($t['pass']) ? '✓' : '✗') . "\n";
    echo "Email: {$t['email']} => " . (isEmail($t['email']) ? '✓' : '✗') . "\n";
    echo "---\n";
}

正則詳解

正則片段含義
^[a-zA-Z]首字符必須是英文字母
[a-zA-Z0-9._]{3,19}後續 3-19 位:字母、數字、下劃線、點
^\w{4,20}$全串 4-20 位單詞字符 (字母數字下劃線)
[a-zA-Z0-9._%+-]+郵箱本地部:允許特殊字符 ._%+-
[a-zA-Z0-9.-]+域名部分:字母數字點連字符
\.[a-zA-Z]{2,}頂級域:點 + 2位以上字母

增強版密碼策略 (推薦生產環境)

function isStrongPassword(string $pwd): array {
    $checks = [
        'length'   => strlen($pwd) >= 8,
        'upper'    => preg_match('/[A-Z]/', $pwd),
        'lower'    => preg_match('/[a-z]/', $pwd),
        'digit'    => preg_match('/\d/', $pwd),
        'special'  => preg_match('/[!@#$%^&*()_+\-=\[\]{};\':"\\|,.<>\/?]/', $pwd),
    ];
    
    $score = array_sum($checks);
    $messages = [];
    foreach ($checks as $k => $v) if (!$v) $messages[] = "缺少: " . ['length'=>'8位長度','upper'=>'大寫','lower'=>'小寫','digit'=>'數字','special'=>'特殊字符'][$k];
    
    return [
        'valid' => $score >= 4,  // 至少滿足 4 條
        'score' => $score,
        'messages' => $messages
    ];
}

// 使用
$result = isStrongPassword('Abc12345');  // valid=true, score=4
$result = isStrongPassword('abc123');    // valid=false, score=2, messages=['缺少: 大寫','缺少: 特殊字符']

前端配合:HTML5 原生驗證

<form>
  <input type="text" name="username" 
         pattern="[a-zA-Z][a-zA-Z0-9._]{3,19}" 
         title="字母開頭,4-20位字母數字下劃線點" required>
  
  <input type="password" name="password"
         pattern="\w{4,20}"
         title="4-20位字母數字下劃線" required>
  
  <input type="email" name="email" required>
  
  <button type="submit">註冊</button>
</form>

安全補充

  • **後端必須驗證**:前端可繞過,正則僅為首道防線
  • **密碼存儲**:永遠不存明文,使用 `password_hash()` + `password_verify()`
  • **防暴力破解**:登錄限流、賬號鎖定、雙因子認證 (2FA)
  • **用戶名唯一性**:數據庫唯一索引 + 註冊時查重

總結

基礎驗證三件套:isEmail、isUsername (字母開頭)、isPassword (字母數字組合)。生產環境建議升級為強密碼策略 (長度+大小寫+數字+特殊字符),並配合 `password_hash()`、限流、2FA 構建完整認證安全體系。

copyright © 萬盛學電腦網 all rights reserved