萬盛學電腦網

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

PHP 註冊表單驗證器實現:從規則定義到資料持久化

設計目標

  • 職責單一:驗證邏輯與控制器分離
  • 可擴展:易於新增欄位與規則
  • 安全:防 XSS、SQL 注入、弱密碼

核心驗證類

<?php
final class RegisterValidator
{
    /** @return Error[] */
    public static function validate(string $username, string $password, string $repeatPassword, string $email): array
    {
        $errors = [];
        $username = trim($username);
        $password = trim($password);
        $repeatPassword = trim($repeatPassword);
        $email = trim($email);

        // 用戶名
        if ($username === '') {
            $errors[] = new Error('username', '用戶名不能為空');
        } elseif (mb_strlen($username) < 3) {
            $errors[] = new Error('username', '用戶名長度至少 3 字元');
        } elseif (mb_strlen($username) > 30) {
            $errors[] = new Error('username', '用戶名長度不超過 30 字元');
        } elseif (!preg_match('/^[A-Za-z]/', $username)) {
            $errors[] = new Error('username', '用戶名必須以字母開頭');
        } elseif (!preg_match('/^[A-Za-z0-9_]+$/', $username)) {
            $errors[] = new Error('username', '用戶名僅允許字母、數字、底線');
        }

        // 密碼
        if ($password === '') {
            $errors[] = new Error('password', '密碼不能為空');
        } elseif (mb_strlen($password) < 8) {
            $errors[] = new Error('password', '密碼長度至少 8 字元');
        } elseif (!preg_match('/[A-Za-z]/', $password) || !preg_match('/\d/', $password)) {
            $errors[] = new Error('password', '密碼需包含字母與數字');
        } elseif ($password !== $repeatPassword) {
            $errors[] = new Error('password', '兩次輸入密碼不一致');
        }

        // Email
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors[] = new Error('email', '郵箱格式不正確');
        }

        // 業務唯一性檢查(延遲到無格式錯誤時執行)
        if (empty($errors)) {
            $dao = new UserDao();
            if ($dao->findByName($username)) {
                $errors[] = new Error('username', '用戶名已被佔用');
            }
            if ($dao->findByEmail($email)) {
                $errors[] = new Error('email', '郵箱已被註冊');
            }
        }

        return $errors;
    }
}

class Error {
    public string $field;
    public string $message;
    public function __construct(string $field, string $message) {
        $this->field = $field;
        $this->message = $message;
    }
}
?>

控制器調用範例

<?php
session_start();
require_once 'config.php';
require_once 'RegisterValidator.php';
require_once 'UserDao.php';
require_once 'User.php';

$username = $password = $repeat = $email = '';
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    $repeat   = $_POST['repeat_password'] ?? '';
    $email    = trim($_POST['email'] ?? '');

    $errors = RegisterValidator::validate($username, $password, $repeat, $email);

    if (empty($errors)) {
        $dao = new UserDao();
        $user = new User();
        $user->setEmail($email);
        $user->setUsername($username);
        $salt = bin2hex(random_bytes(16));
        $user->setPassword(hash('sha256', $salt . $password));
        $user->setSalt($salt);
        $user->setLastLoginIp($_SERVER['REMOTE_ADDR'] ?? '');

        if ($dao->save($user)) {
            $_SESSION['user_id'] = $user->getId();
            header('Location: welcome.php');
            exit;
        } else {
            $errors[] = new Error('system', '註冊失敗,請稍後再試');
        }
    }
}

// 視圖渲染(略)
?>

安全加固清單

  1. 密碼使用 bcrypt/argon2:`password_hash($pwd, PASSWORD_ARGON2ID)`
  2. CSRF 保護:表單隱藏欄位 `_token` + Session 驗證
  3. 限流:同 IP 分鐘內註冊嘗試次數限制
  4. Honeypot 隱藏欄位防機器人
  5. HTTPS 全站強制
copyright © 萬盛學電腦網 all rights reserved