用戶認證是 Web 應用核心。本文提供一個功能完整的 Auth 類別,涵蓋 **Session/Cookie 雙重驗證、密碼雜湊加鹽、IP 綁定防竊、登入/登出/自動驗證** 等實戰功能,並針對原始碼中的安全性問題(SQL 注入、MD5 弱雜湊、mysql_* 棄用)進行現代化重構說明。
⚠️ 原始碼使用
mysql_*(PHP 7.0 移除)、MD5(不可逆但極弱)、字串拼接 SQL(注入風險)。生產環境請務必重構為 PDO + password_hash() + 預處理語句。
<?php
// 連線單例
class DB {
private static ?PDO $pdo = null;
public static function pdo(): PDO {
return self::$pdo ??= new PDO(
"mysql:host=127.0.0.1;dbname=myapp;charset=utf8mb4",
'user', 'pass',
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false]
);
}
}
?>
password_hash() / password_verify()<?php
// 註冊/設定密碼時
$hash = password_hash($plainPassword, PASSWORD_ARGON2ID); // 或 PASSWORD_BCRYPT
// 登入驗證時
if (password_verify($plainPassword, $hashFromDB)) {
// 成功
// 可選:檢查是否需重新雜湊(演算法升級)
if (password_needs_rehash($hashFromDB, PASSWORD_ARGON2ID)) {
$newHash = password_hash($plainPassword, PASSWORD_ARGON2ID);
// UPDATE users SET password = ? WHERE id = ?
}
}
?>
<?php
$stmt = DB::pdo()->prepare(
"SELECT `id`, `password` FROM `{$this->table}` WHERE `{$this->usernameCol}` = ? LIMIT 1"
);
$stmt->execute([$username]);
$user = $stmt->fetch();
if ($user && password_verify($password, $user['password'])) {
// 登入成功
}
?>
<?php
class Auth
{
// 設定屬性(可透過建構子注入)
public string $table = 'users';
public string $usernameCol = 'email';
public string $passwordCol = 'password';
public string $idCol = 'id';
public int $cookieLifetime = 7200; // 2小時
public string $cookiePath = '/';
public string $cookieDomain = '';
public bool $cookieSecure = true; // 僅 HTTPS
public bool $cookieHttpOnly = true; // 防 XSS
public string $sessionPrefix = 'auth_';
private ?int $userId = null;
private ?string $username = null;
private bool $loggedIn = false;
public function __construct(array $config = [])
{
foreach ($config as $k => $v) {
if (property_exists($this, $k)) $this->$k = $v;
}
}
// 核心:初始化驗證(每請求呼叫一次)
public function init(): bool
{
if ($this->loggedIn !== false) return $this->loggedIn; // 已快取
// 1. 嘗試 Session
if ($this->checkSession()) return $this->loggedIn = true;
// 2. 嘗試 Cookie
if ($this->checkCookie()) return $this->loggedIn = true;
// 3. 都失效
$this->clearAuthData();
return $this->loggedIn = false;
}
private function checkSession(): bool
{
$sid = $this->sessionPrefix . 'uid';
$spw = $this->sessionPrefix . 'pwd_hash';
if (empty($_SESSION[$sid]) || empty($_SESSION[$spw])) return false;
return $this->verifyCredentials($_SESSION[$sid], $_SESSION[$spw]);
}
private function checkCookie(): bool
{
$cid = $this->sessionPrefix . 'uid';
$cpw = $this->sessionPrefix . 'pwd_hash';
if (empty($_COOKIE[$cid]) || empty($_COOKIE[$cpw])) return false;
$uid = (int)$_COOKIE[$cid];
$hash = $_COOKIE[$cpw];
// 綁定 IP 驗證
if ($this->getClientIP() !== $_COOKIE[$this->sessionPrefix . 'ip'] ?? '') {
return false;
}
if ($this->verifyCredentials($uid, $hash)) {
// Cookie 升級為 Session
$_SESSION[$cid] = $uid;
$_SESSION[$spw] = $hash;
return true;
}
return false;
}
private function verifyCredentials(int|string $uid, string $hash): bool
{
// 靜態快取
static $cache = [];
$key = $uid . '|' . $hash;
if (isset($cache[$key])) return $cache[$key] = (bool)($cache[$key] ??= $this->queryUser($uid, $hash));
return $cache[$key] = $this->queryUser($uid, $hash);
}
private function queryUser(int|string $uid, string $hash): bool
{
$stmt = DB::pdo()->prepare(
"SELECT `$this->idCol`, `$this->passwordCol` FROM `$this->table` WHERE `$this->idCol` = ? LIMIT 1"
);
$stmt->execute([$uid]);
$row = $stmt->fetch();
if (!$row) return false;
// 這裡 $hash 是「密碼雜湊的雜湊」或「密碼雜湊本身」,視設計而定
// 簡化:假設 Cookie 存的是 password_hash 結果
return password_verify($hash, $row[$this->passwordCol]);
}
// 登入
public function login(string $username, string $password, bool $remember = false): bool
{
$stmt = DB::pdo()->prepare(
"SELECT `$this->idCol`, `$this->passwordCol` FROM `$this->table` WHERE `$this->usernameCol` = ? LIMIT 1"
);
$stmt->execute([$username]);
$user = $stmt->fetch();
if (!$user || !password_verify($password, $user[$this->passwordCol])) {
return false;
}
$this->userId = (int)$user[$this->idCol];
$this->username = $username;
$this->loggedIn = true;
// 寫入 Session
$_SESSION[$this->sessionPrefix . 'uid'] = $this->userId;
$_SESSION[$this->sessionPrefix . 'pwd_hash'] = $user[$this->passwordCol];
// 記住我:寫入 Cookie
if ($remember) {
$ip = $this->getClientIP();
setcookie($this->sessionPrefix . 'uid', $this->userId, time() + $this->cookieLifetime,
$this->cookiePath, $this->cookieDomain, $this->cookieSecure, $this->cookieHttpOnly);
setcookie($this->sessionPrefix . 'pwd_hash', $user[$this->passwordCol], time() + $this->cookieLifetime,
$this->cookiePath, $this->cookieDomain, $this->cookieSecure, $this->cookieHttpOnly);
setcookie($this->sessionPrefix . 'ip', $ip, time() + $this->cookieLifetime,
$this->cookiePath, $this->cookieDomain, $this->cookieSecure, $this->cookieHttpOnly);
}
return true;
}
// 登出
public function logout(): void
{
$this->clearAuthData();
$this->userId = null;
$this->username = null;
$this->loggedIn = false;
}
private function clearAuthData(): void
{
$keys = ['uid', 'pwd_hash', 'ip'];
foreach ($keys as $k) {
$name = $this->sessionPrefix . $k;
unset($_SESSION[$name]);
setcookie($name, '', time() - 3600, $this->cookiePath, $this->cookieDomain, $this->cookieSecure, $this->cookieHttpOnly);
}
}
public function getUserId(): ?int { return $this->userId; }
public function getUsername(): ?string { return $this->username; }
public function isLoggedIn(): bool { return $this->loggedIn; }
private function getClientIP(): string
{
foreach (['HTTP_CF_CONNECTING_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP', 'REMOTE_ADDR'] as $key) {
if (!empty($_SERVER[$key])) {
$ips = explode(',', $_SERVER[$key]);
return trim($ips[0]);
}
}
return '0.0.0.0';
}
}
?>
<?php
require 'Auth.php';
session_start();
$auth = new Auth([
'table' => 'users',
'usernameCol' => 'email',
'cookieSecure' => true, // 僅 HTTPS
]);
// 處理登入表單
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['login'])) {
if ($auth->login($_POST['email'], $_POST['password'], $_POST['remember'] ?? false)) {
header('Location: /dashboard.php');
exit;
}
$error = '帳號或密碼錯誤';
}
// 每頁頂部驗證
if (!$auth->init()) {
header('Location: /login.php');
exit;
}
echo "歡迎,{$auth->getUsername()} (ID: {$auth->getUserId()})";
?>
password_hash() / password_verify()(Argon2id/Bcrypt)HttpOnly、Secure、SameSite=Lax這個 Auth 類別提供了堅實的認證基礎,配合現代 PHP 安全實踐,即可構建可靠的用戶登入系統。