PHP setrawcookie 函数
最后修改于 2025 年 4 月 4 日
PHP 的 setrawcookie 函数发送一个原始 Cookie,不进行 URL 编码。当您需要精确控制 Cookie 值时,它非常有用。
基本定义
setrawcookie 定义一个要随 HTTP 标头一起发送的 Cookie。与 setcookie 不同,它不会对 Cookie 值进行 URL 编码。
语法:setrawcookie(string $name, string $value = "", array $options = []): bool。必须在将任何输出发送到浏览器之前调用。
基本原始 Cookie 示例
此示例演示了设置一个带有名称和值的简单原始 Cookie。
<?php
declare(strict_types=1);
setrawcookie("user_token", "abc123XYZ!@#");
echo "Raw cookie set successfully";
Cookie 值将完全按照提供的方式保留,不应用任何 URL 编码。像 !@# 这样的特殊字符将以其原始形式保留。
带过期时间的 Cookie
这展示了如何设置一个具有特定过期时间的原始 Cookie。
<?php
declare(strict_types=1);
$expire = time() + 3600; // 1 hour from now
setrawcookie("session_id", "raw_value_!@#", [
'expires' => $expire
]);
echo "Cookie will expire in 1 hour";
过期时间使用选项数组中的 'expires' 选项设置。Cookie 将在指定的 Unix 时间戳后自动过期。
安全和 HttpOnly Cookie
此示例创建了一个安全、HttpOnly 的原始 Cookie,以增强安全性。
<?php
declare(strict_types=1);
setrawcookie("auth_token", "secure!raw#value", [
'secure' => true,
'httponly' => true,
'samesite' => 'Strict'
]);
echo "Secure HttpOnly cookie set";
'secure' 标志确保 Cookie 仅通过 HTTPS 发送。HttpOnly 可防止 JavaScript 访问,SameSite 限制跨站使用。
域和路径受限 Cookie
这演示了设置一个受限于特定域和路径的原始 Cookie。
<?php
declare(strict_types=1);
setrawcookie("preferences", "dark_theme=true", [
'domain' => '.example.com',
'path' => '/settings',
'expires' => time() + 86400
]);
echo "Domain and path restricted cookie set";
该 Cookie 将仅发送到 example.com 及其子域。它进一步限制在 /settings 路径下的 URL。
带特殊字符的 Cookie
此示例展示了 setrawcookie 如何保留值中的特殊字符。
<?php
declare(strict_types=1);
$rawValue = "user@domain.com|token=ABC123!*()";
setrawcookie("user_data", $rawValue);
echo "Cookie with special characters set without encoding";
包含 @、|、= 和 !*() 的原始值被精确保留。使用 setcookie,这些字符将被 URL 编码,从而改变值。
最佳实践
- 安全: 敏感 Cookie 务必使用 secure 和 HttpOnly 标志
- 时机: 在任何输出之前调用,以避免“Headers already sent”错误
- 验证: 由于它们未进行 URL 编码,请对值进行清理
- 大小限制: 保持在 4KB 的浏览器 Cookie 大小限制之内
来源
本教程通过在各种场景下设置原始 Cookie 的实际示例,介绍了 PHP setrawcookie 函数。
作者
列出 所有 PHP 网络函数。