後台管理系統的核心安全需求是:未登入用戶無法直接訪問任何後台頁面。本文提供一套完整的三檔案實作範例:登入頁、驗證處理頁、受保護後台頁,展示 Session 驗證攔截的標準流程與關鍵安全細節。
admin/
├── login.php # 登入頁面(表單 + 錯誤顯示)
├── loginProcess.php # 登入驗證邏輯(Session 建立)
└── admin.php # 受保護後台頁(Session 攔截檢查)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>後台登入</title>
<style>body{font-family:Microsoft YaHei;max-width:400px;margin:100px auto;}</style>
</head>
<body>
<h2>後台管理登入</h2>
<form action="loginProcess.php" method="post">
<div><label>用戶名:</label><input type="text" name="username" required></div>
<div><label>密碼:</label><input type="password" name="pwd" required></div>
<button type="submit" name="sub">登入後台</button>
</form>
<?php
// 顯示錯誤訊息(透過 GET 參數傳遞)
if (!empty($_GET['errno'])) {
$msg = [
1 => '用戶名或密碼錯誤',
2 => '請輸入用戶名和密碼',
3 => '非法訪問,請先登入'
];
echo '<p style="color:red">' . ($msg[$_GET['errno']] ?? '未知錯誤') . '</p>';
}
?>
</body>
</html>
<?php
// 僅處理 POST 提交
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || empty($_POST['sub'])) {
header("Location: login.php?errno=2");
exit;
}
$username = trim($_POST['username']);
$password = $_POST['pwd'];
// 簡單示範驗證(實際專案應查詢資料庫、驗證密碼雜湊)
if ($username === 'admin' && $password === 'admin') {
// 驗證通過:建立 Session
session_start();
// 關鍵安全:重新生成 Session ID,防止 Session Fixation 攻擊
session_regenerate_id(true);
$_SESSION['admin'] = [
'uid' => 1,
'username' => $username,
'login_at' => time(),
'ip' => $_SERVER['REMOTE_ADDR']
];
// 登入成功跳轉後台
header("Location: admin.php");
exit;
} else {
header("Location: login.php?errno=1");
exit;
}
?>
<?php
// 必須最先執行:啟動 Session
session_start();
// 核心攔截邏輯:檢查登入標記
if (empty($_SESSION['admin']['uid'])) {
// 未登入:重導向登入頁,攜帶錯誤代碼
header("Location: login.php?errno=3");
exit;
}
// 可選:檢查 Session 過期(滑動過期由 PHP 自動管理,這裡可加業務邏輯)
// if (time() - $_SESSION['admin']['login_at'] > 3600) { ... }
// 可選:檢查 IP 變更(防止 Session 劫持)
// if ($_SESSION['admin']['ip'] !== $_SERVER['REMOTE_ADDR']) { ... }
// 通過驗證:顯示後台內容
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>後台管理首頁</title>
</head>
<body>
<h1>歡迎,<?= htmlspecialchars($_SESSION['admin']['username']) ?>!</h1>
<p>您現在擁有後台管理權限。</p>
<hr>
<a href="logout.php">安全登出</a>
</body>
</html>
<?php
session_start();
// 刪除伺服器端 Session 檔案
session_destroy();
// 刪除客戶端 Session Cookie
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
header("Location: login.php");
exit;
?>
header("Location: ...) 後必須 exit(),防止後續代碼繼續執行洩露資料password_hash() / password_verify()
// 在 admin.php 攔截器中擴充
$requiredPermission = 'article_edit'; // 當前頁面所需權限
$userPermissions = getUserPermissions($_SESSION['admin']['uid']); // 從資料庫/快取獲取
if (!in_array($requiredPermission, $userPermissions)) {
header("HTTP/1.1 403 Forbidden");
exit('權限不足');
}
此三檔案模式是 PHP 後台權限控制的最小可行核心,掌握其原理可輕鬆擴充至複雜的 RBAC、多租戶、OAuth2 整合等企業級架構。