在页面之间记住你的访客:安全的登录、基于会话的购物车,以及得到妥善保护的 Cookie。
在 Kodokon 中打开本课HTTP 什么都不记得:每个请求都是全新到达的,和前一个请求没有任何关联。会话解决了这个问题:session_start() 会把访客和一个唯一标识符关联起来(该标识符通过 Cookie 传输),并关联一块位于服务器端、可通过 $_SESSION 访问的存储空间。请在每个相关页面的最顶部、任何输出之前调用 session_start()。
<?php
declare(strict_types=1);
session_start();
$storedHash = password_hash('secret123', PASSWORD_DEFAULT);
$password = $_POST['password'] ?? '';
if (password_verify($password, $storedHash)) {
session_regenerate_id(true);
$_SESSION['user_id'] = 42;
header('Location: /account.php');
exit;
}
echo "Invalid credentials.";保护一个页面归结为检查用户是否存在于会话中,否则就进行重定向。会话也是购物车的理想临时存储:一个 商品 id => 数量 的关联数组能在页面之间一直保留。
<?php
declare(strict_types=1);
session_start();
if (!isset($_SESSION['user_id'])) {
header('Location: /login.php');
exit;
}
$_SESSION['cart'] ??= [];
$productId = filter_input(
INPUT_POST,
'product_id',
FILTER_VALIDATE_INT
);
if (is_int($productId)) {
$qty = $_SESSION['cart'][$productId] ?? 0;
$_SESSION['cart'][$productId] = $qty + 1;
}
$count = array_sum($_SESSION['cart']);
echo "Cart: " . $count . " item(s)";Cookie 则不同,它存在于用户的设备上,并且在关闭浏览器后依然存在:非常适合保存主题或语言偏好。自 PHP 7.3 起,setcookie() 接受一个选项数组:请务必设置 secure(仅限 HTTPS)、httponly(对 JavaScript 不可见)和 samesite(限制从其他站点发送)。
<?php
setcookie('theme', 'dark', [
'expires' => time() + 60 * 60 * 24 * 30,
'path' => '/',
'secure' => true,
'httponly' => true,
'samesite' => 'Lax',
]);
$theme = $_COOKIE['theme'] ?? 'light';
echo "Active theme: " . $theme;退出登录必须和登录一样谨慎地完成:清空 $_SESSION,在服务器端销毁会话,并让承载标识符的 Cookie 过期。
<?php
session_start();
$_SESSION = [];
session_destroy();
setcookie(session_name(), '', time() - 3600, '/');
header('Location: /login.php');
exit;