PHP 会话:登录、退出与保护会员页面

PHP 登录流程先验证密码,再更新会话 ID,并将用户 ID 保存到 $_SESSION。会员页面在输出正文前,在服务器端检查会话及其有效期。退出时清理服务器会话和 Cookie。

准备本地练习文件

准备 PHP 8.x 和 login-demo 目录,按下方结构保存文件。使用无 BOM 的 UTF-8,并只公开 public。账号文件和会话数据放在 app。这个回环地址练习使用公开账号 demo 和练习密码 sample-only passphrase 42。

login-demo/
  create-demo-user.php
  app/
    bootstrap.php
    demo-user.php
    sessions/
  public/
    login.php
    content.php
    logout.php

生成练习账号的密码哈希

在命令行运行 create-demo-user.php。它生成练习密码的哈希并创建 app/demo-user.php,不会覆盖已有文件。生成与保存见密码哈希生成和保存示例。

<?php
declare(strict_types=1);
if (PHP_SAPI !== 'cli') {
    http_response_code(403);
    exit('请从命令行运行。');
}
$dir = __DIR__ . '/app';
if (!is_dir($dir) && !mkdir($dir, 0700, true)) {
    throw new RuntimeException('无法创建 app 目录。');
}
$record = [
    'id' => 'demo',
    'username' => 'demo',
    'password_hash' => password_hash('sample-only passphrase 42', PASSWORD_DEFAULT),
];
$source = "<?php\nreturn " . var_export($record, true) . ";\n";
$file = fopen($dir . '/demo-user.php', 'x');
if ($file === false) {
    throw new RuntimeException('账号文件已存在或无法创建,未覆盖该文件。');
}
$written = fwrite($file, $source);
fclose($file);
if ($written !== strlen($source)) {
    throw new RuntimeException('未能完整写入账号文件。');
}
echo '已生成练习账号文件。', PHP_EOL;

配置会话与过期时间

app/bootstrap.php 启用仅通过 Cookie 传递 ID 的配置和严格模式。本地 HTTP Cookie 使用 HttpOnly 与 SameSite=Lax。登录满一小时或闲置 15 分钟后,服务器使会话过期。生产环境应按实际部署配置 HTTPS、Secure Cookie 与会话存储。 PHP Manual · Session Security PHP Manual · Session Management

<?php
declare(strict_types=1);
if (!in_array($_SERVER['REMOTE_ADDR'] ?? '', ['127.0.0.1', '::1'], true)) {
    http_response_code(403);
    exit('本练习仅限本地运行。');
}
$sessionDir = __DIR__ . '/sessions';
if (!is_dir($sessionDir) && !mkdir($sessionDir, 0700, true)) {
    http_response_code(500);
    exit('无法准备会话存储。');
}
ini_set('session.use_strict_mode', '1');
ini_set('session.use_only_cookies', '1');
ini_set('session.use_trans_sid', '0');
session_save_path($sessionDir);
session_name('CFLOGINDEMO');
session_set_cookie_params([
    'lifetime' => 0, 'path' => '/', 'domain' => '', 'secure' => false,
    'httponly' => true, 'samesite' => 'Lax',
]);
if (!session_start()) {
    http_response_code(500);
    exit('无法启动会话。');
}
header('Content-Type: text/html; charset=UTF-8');
header('Cache-Control: no-store');

function e(string $value): string {
    return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
function csrfToken(): string {
    if (!isset($_SESSION['csrf']) || !is_string($_SESSION['csrf'])) {
        $_SESSION['csrf'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf'];
}
function validCsrf(mixed $token): bool {
    return is_string($token) && hash_equals(csrfToken(), $token);
}
function redirectTo(string $path): void {
    if (session_status() === PHP_SESSION_ACTIVE) {
        session_write_close();
    }
    header('Location: ' . $path, true, 303);
    exit;
}
function isLoggedIn(): bool {
    if (($_SESSION['user_id'] ?? null) !== 'demo') {
        return false;
    }
    $created = $_SESSION['logged_in_at'] ?? null;
    $lastSeen = $_SESSION['last_seen'] ?? null;
    $now = time();
    if (!is_int($created) || !is_int($lastSeen)
        || $now - $created >= 3600 || $now - $lastSeen >= 900) {
        unset($_SESSION['user_id'], $_SESSION['logged_in_at'], $_SESSION['last_seen']);
        $_SESSION['csrf'] = bin2hex(random_bytes(32));
        return false;
    }
    $_SESSION['last_seen'] = $now;
    return true;
}

登录和退出的 POST 校验会话令牌,以防御跨站请求伪造(CSRF)。跳转使用固定的内部路径,并在发送 HTTP 303 后结束脚本。 OWASP · CSRF Prevention PHP 跳转示例

验证密码后更新会话 ID

GET 显示 public/login.php 的表单,POST 校验令牌和输入。用户名或密码错误时显示同一提示。密码中的空格保留。72 字节是该示例的 bcrypt 兼容限制。 password_verify() 验证示例

<?php
declare(strict_types=1);
require_once __DIR__ . '/../app/bootstrap.php';
if (isLoggedIn()) {
    redirectTo('/content.php');
}
$error = '';
$username = '';
$method = $_SERVER['REQUEST_METHOD'] ?? '';
if ($method === 'POST') {
    if (!validCsrf($_POST['csrf'] ?? null)) {
        http_response_code(403);
        exit('请重新打开表单。');
    }
    $rawUser = $_POST['username'] ?? null;
    $password = $_POST['password'] ?? null;
    if (!is_string($rawUser) || !is_string($password)
        || strlen($rawUser) > 80 || strlen($password) > 72
        || $password === '' || str_contains($password, "\0")) {
        http_response_code(422);
        $error = '请检查输入格式与长度。';
    } else {
        $username = trim($rawUser);
        $accountFile = __DIR__ . '/../app/demo-user.php';
        if (!is_readable($accountFile)) {
            http_response_code(500);
            exit('未能完成登录。');
        }
        $user = require $accountFile;
        $passwordOK = password_verify($password, $user['password_hash']);
        if ($username !== $user['username'] || !$passwordOK) {
            http_response_code(401);
            $error = '用户名或密码不正确。';
        } else {
            if (!session_regenerate_id(false)) {
                http_response_code(500);
                exit('未能完成登录。');
            }
            $now = time();
            $_SESSION = [
                'user_id' => $user['id'], 'logged_in_at' => $now,
                'last_seen' => $now, 'csrf' => bin2hex(random_bytes(32)),
            ];
            redirectTo('/content.php');
        }
    }
} elseif ($method !== 'GET') {
    http_response_code(405);
    header('Allow: GET, POST');
    exit;
}
$csrf = csrfToken();
session_write_close();
?>
<!doctype html>
<html lang="zh">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>本地登录练习</title></head>
<body>
<h1>登录练习</h1>
<?php if ($error !== ''): ?><p><?= e($error) ?></p><?php endif; ?>
<form method="post" action="/login.php">
  <input type="hidden" name="csrf" value="<?= e($csrf) ?>">
  <p><label>用户名 <input name="username" value="<?= e($username) ?>" autocomplete="username" required></label></p>
  <p><label>密码 <input type="password" name="password" autocomplete="current-password" required></label></p>
  <button>登录</button>
</form>
<p><a href="/content.php">检查会员内容的访问权限</a></p>
</body>
</html>

验证成功后,通过 session_regenerate_id(false) 更新 ID,再把身份状态写入新会话。旧的匿名会话暂时保留,但没有登录状态。有并发请求的生产环境应另行设计 ID 更新与淘汰。 PHP Manual · session_regenerate_id()

在服务器端保护会员页面

public/content.php 先调用 isLoggedIn()。未登录或已过期时跳回登录页,响应不包含会员内容。即使浏览器还保留 Cookie,服务器的期限仍有效。

<?php
declare(strict_types=1);
require_once __DIR__ . '/../app/bootstrap.php';
if (!isLoggedIn()) {
    redirectTo('/login.php');
}
$userId = $_SESSION['user_id'];
$csrf = csrfToken();
session_write_close();
?>
<!doctype html>
<html lang="zh">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>会员内容练习</title></head>
<body>
<h1>会员内容</h1>
<p>已登录的账号:<?= e($userId) ?></p>
<p>这是会员专用的示例内容。</p>
<form method="post" action="/logout.php">
  <input type="hidden" name="csrf" value="<?= e($csrf) ?>">
  <button>退出登录</button>
</form>
</body>
</html>

用 POST 退出并清理 Cookie

public/logout.php 对 GET 返回 405,对缺少有效令牌的 POST 返回 403。只有符合条件的 POST 才会清空数组并删除服务器数据,再用匹配的名称、路径和域让 Cookie 过期,然后跳回登录。 PHP Manual · session_destroy()

<?php
declare(strict_types=1);
require_once __DIR__ . '/../app/bootstrap.php';
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
    http_response_code(405);
    header('Allow: POST');
    exit('请使用退出按钮。');
}
if (!validCsrf($_POST['csrf'] ?? null)) {
    http_response_code(403);
    exit('请重新打开表单。');
}
$name = session_name();
$params = session_get_cookie_params();
$_SESSION = [];
if (!session_destroy()) {
    http_response_code(500);
    exit('未能完成退出。');
}
setcookie($name, '', [
    'expires' => time() - 3600, 'path' => $params['path'],
    'domain' => $params['domain'],
    'secure' => $params['secure'], 'httponly' => $params['httponly'],
    'samesite' => $params['samesite'],
]);
header('Location: /login.php', true, 303);
exit;

运行并检查结果

在项目目录按顺序运行两个命令。服务器只在 127.0.0.1 监听。端口被占用时同时修改命令与 URL。结束后按 Ctrl+C。如果会话无法保持,检查 URL、Cookie 是否发送和 app/sessions 的写权限。

php create-demo-user.php
php -S 127.0.0.1:8000 -t public
  1. 先打开 http://127.0.0.1:8000/content.php。应跳转到登录表单,且没有会员文案。
  2. 提交错误密码。应显示通用提示并继续限制会员页面。
  3. 用 demo 与公开练习密码登录。刷新仍能查看会员内容,另一个浏览器配置需要重新登录。
  4. 点退出按钮再打开 content.php,应回到登录表单且没有受保护的内容。

设计生产环境的认证与权限

生产系统应优先考虑经过验证的认证组件。设计账号状态、资源权限、尝试次数限制、多因素认证、恢复和会话失效机制。Cache-Control: no-store 控制响应缓存。服务器还要在每条受保护路由判断访问权限。 OWASP · Authentication OWASP · Session Management