蓝色天空网mbsky.com · 知识 · 实践 · 创造PHP · 本地阅读预览
教程 / 后端开发 / PHP

PHP 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 · 阅读源码
<?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";
预期结果 · 待实际运行核验
  • 核对 urlencode vs raw 编码与 1 小时/30 天 GMT 过期头、Cookie 请求头解析与 isset 分支、过去时间戳删除头及无 Cookie 表单回退。
运行 Set-Cookie 编码与过期头、Cookie 解析、过去时间删除及表单回退实验

所需环境:Windows x64、PHP 8.4 本地 CLI 环境。

当前源码 SHA256:dd2f0051e8e7818a851575d0de64acc5536f7e9ebae2fe124488d6e3be6a2b35

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载PHP Cookie实验

所需环境:Windows x64、PHP 8.4 本地 CLI 环境。

ZIP SHA256:4abd39902b8eab917d464ff8886c47913b6971c4deebb3fd2b2bbb9469803212

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

为什么 setcookie() 必须在 <html> 标签或任何 echo 输出之前调用?

展开参考解答

setcookie() 本质上是向 HTTP 响应添加 Set-Cookie 头部字段,一旦脚本向客户端输出了响应体字节,HTTP 响应头即已发送完毕,之后再调用 setcookie() 会失败并触发 headers already sent 警告。

规范与官方依据