PHP Cookie
核对 Cookie 识别机制、setcookie()/setrawcookie() 响应头发送时机与 URL 编解码规则、$_COOKIE 读取与 isset() 判空、过期删除及无 Cookie 浏览器表单回退方案。
学完这一章,你能够
- 核对 Cookie 识别机制、setcookie()/setrawcookie() 响应头发送时机与 URL 编解码规则、$_COOKIE 读取与 isset() 判空、过期删除及无 Cookie 浏览器表单回退方案。
Cookie 概念与创建方式
Cookie 是服务器下发并保存在客户端浏览器上的小型键值对数据,常用于识别访客身份与偏好设置;此后同一浏览器再次请求匹配域名与路径的页面时,会自动在请求头中附带对应 Cookie。
PHP 使用 `setcookie(name, value, expire, path, domain, ...)` 通过 HTTP `Set-Cookie` 响应头创建 Cookie,因此必须在任何 HTML 或正文输出之前调用。发送时 `setcookie()` 会自动对值执行 URL 编码、读取时自动解码(若需禁用自动编码可改用 `setrawcookie()`)。过期时间以 Unix 秒时间戳指定,例如 `time() + 3600` 表示 1 小时后失效,`time() + 60*60*24*30`(`2592000` 秒)表示 30 天后失效。本站 PHP 8.4.27 实测基准时间 `2026-01-01 12:00:00 UTC` 下:`setcookie` 规则把 `"blue sky+1"` 编码为 `user=blue+sky%2B1; Expires=Thu, 01 Jan 2026 13:00:00 GMT; Path=/; HttpOnly`,30 天后 GMT 时刻为 `Sat, 31 Jan 2026 12:00:00 GMT`。
读取、删除 Cookie 与无 Cookie 回退
服务端通过超全局数组 `$_COOKIE` 获取浏览器回传的值,并应先用 `isset($_COOKIE["user"])` 判断是否存在再输出(同时做 `htmlspecialchars()` 转义防 XSS),避免访问未定义键产生警告。本站实测解析请求头 `user=alice+lin; theme=dark` 后还原 `user="alice lin"` 并命中欢迎分支,空 Cookie 头则回退输出 `"普通访客!"`。
删除 Cookie 的标准方式是重发同名同路径的 `setcookie()` 并把过期时间设为过去时刻(如 `time() - 3600`)且清空值,浏览器收到后立即将其移除。本站实测删除头输出 `Set-Cookie: user=; Expires=Thu, 01 Jan 2026 11:00:00 GMT; Path=/; HttpOnly`(早于当前基准时间)。
若客户端禁用了 Cookie,应用程序可改用表单 POST(或服务端显式令牌)在页面间传递必要状态:例如将用户姓名与年龄提交至 `welcome.php` 并从 `$_POST` 读取。本站实测空 Cookie 环境下经 POST 表单传递 `name=林青&age=22` 仍可正常输出 `"欢迎 林青,你 22 岁了。"`。
运行 Set-Cookie 编码与过期头、Cookie 解析、过去时间删除及表单回退实验
展开查看收起
<?php
declare(strict_types=1);
date_default_timezone_set('UTC');
function format_set_cookie_header(string $name, string $value, int $expires, string $path = '/', bool $raw = false, bool $httpOnly = true): string
{
$encoded = $raw ? $value : urlencode($value);
$parts = ["{$name}={$encoded}"];
if ($expires !== 0) {
$parts[] = 'Expires=' . gmdate('D, d M Y H:i:s \G\M\T', $expires);
}
if ($path !== '') {
$parts[] = "Path={$path}";
}
if ($httpOnly) {
$parts[] = 'HttpOnly';
}
return 'Set-Cookie: ' . implode('; ', $parts);
}
function parse_cookie_header(string $header): array
{
$cookies = [];
foreach (explode(';', $header) as $pair) {
$pair = trim($pair);
if ($pair === '' || !str_contains($pair, '=')) {
continue;
}
[$k, $v] = explode('=', $pair, 2);
$cookies[trim($k)] = urldecode(trim($v));
}
return $cookies;
}
$cases = [];
// Case 1: Set-Cookie header formatting, urlencode vs setrawcookie, 1h and 30d expiry
(function () use (&$cases): void {
$baseTs = mktime(12, 0, 0, 1, 1, 2026);
$oneHour = $baseTs + 3600;
$thirtyDaysSeconds = 60 * 60 * 24 * 30;
$thirtyDays = $baseTs + $thirtyDaysSeconds;
$actual = [
'encoded_1h' => format_set_cookie_header('user', 'blue sky+1', $oneHour, '/', false, true),
'raw_1h' => format_set_cookie_header('user', 'blue_sky', $oneHour, '/', true, true),
'thirty_days_seconds' => $thirtyDaysSeconds,
'thirty_days_gmt' => gmdate('D, d M Y H:i:s \G\M\T', $thirtyDays),
];
$expected = [
'encoded_1h' => 'Set-Cookie: user=blue+sky%2B1; Expires=Thu, 01 Jan 2026 13:00:00 GMT; Path=/; HttpOnly',
'raw_1h' => 'Set-Cookie: user=blue_sky; Expires=Thu, 01 Jan 2026 13:00:00 GMT; Path=/; HttpOnly',
'thirty_days_seconds' => 2592000,
'thirty_days_gmt' => 'Sat, 31 Jan 2026 12:00:00 GMT',
];
$cases[] = [
'name' => 'setcookie_header_and_url_encoding',
'passed' => $actual === $expected,
'expected' => $expected,
'actual' => $actual,
];
})();
// Case 2: Parsing incoming Cookie header into $_COOKIE and isset() branching
(function () use (&$cases): void {
$cookies = parse_cookie_header('user=alice+lin; theme=dark');
$greetingPresent = isset($cookies['user']) ? '欢迎 ' . htmlspecialchars($cookies['user'], ENT_QUOTES, 'UTF-8') . '!' : '普通访客!';
$emptyCookies = parse_cookie_header('');
$greetingAbsent = isset($emptyCookies['user']) ? '欢迎 ' . $emptyCookies['user'] . '!' : '普通访客!';
$actual = [
'parsed' => $cookies,
'greeting_present' => $greetingPresent,
'greeting_absent' => $greetingAbsent,
];
$expected = [
'parsed' => ['user' => 'alice lin', 'theme' => 'dark'],
'greeting_present' => '欢迎 alice lin!',
'greeting_absent' => '普通访客!',
];
$cases[] = [
'name' => 'cookie_header_parse_and_isset',
'passed' => $actual === $expected,
'expected' => $expected,
'actual' => $actual,
];
})();
// Case 3: Deleting cookie by setting expiration timestamp in the past
(function () use (&$cases): void {
$baseTs = mktime(12, 0, 0, 1, 1, 2026);
$pastTs = $baseTs - 3600;
$deleteHeader = format_set_cookie_header('user', '', $pastTs, '/', false, true);
$actual = [
'is_in_past' => $pastTs < $baseTs,
'delete_header' => $deleteHeader,
];
$expected = [
'is_in_past' => true,
'delete_header' => 'Set-Cookie: user=; Expires=Thu, 01 Jan 2026 11:00:00 GMT; Path=/; HttpOnly',
];
$cases[] = [
'name' => 'cookie_delete_past_expiry',
'passed' => $actual === $expected,
'expected' => $expected,
'actual' => $actual,
];
})();
// Case 4: Fallback form POST transport when browser does not support cookies
(function () use (&$cases): void {
$cookies = [];
$post = [];
parse_str('name=' . rawurlencode('林青') . '&age=22', $post);
$actual = [
'cookie_available' => isset($cookies['user']),
'fallback_greeting' => '欢迎 ' . htmlspecialchars((string)$post['name'], ENT_QUOTES, 'UTF-8') . ',你 ' . (int)$post['age'] . ' 岁了。',
];
$expected = [
'cookie_available' => false,
'fallback_greeting' => '欢迎 林青,你 22 岁了。',
];
$cases[] = [
'name' => 'cookie_disabled_form_fallback',
'passed' => $actual === $expected,
'expected' => $expected,
'actual' => $actual,
];
})();
echo json_encode(['version' => PHP_VERSION, 'cases' => $cases], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n";
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
setcookie() 本质上是向 HTTP 响应添加 Set-Cookie 头部字段,一旦脚本向客户端输出了响应体字节,HTTP 响应头即已发送完毕,之后再调用 setcookie() 会失败并触发 headers already sent 警告。