Cookie 类
功能概述
Cookie 类提供了简便的 Cookie 操作方法,包括设置、获取、检查、删除和批量获取 Cookie 数据,同时支持 Cookie 前缀管理和值过滤功能。
基本用法
设置 Cookie
// 基本设置(键、值)
Cookie::set('user_id', 1001);
// 设置有效期(30天)
Cookie::set('remember', 'yes', [
'expire' => time() + 86400 * 30
]);
// 设置安全选项
Cookie::set('token', 'abc123', [
'expire' => time() + 3600,
'path' => '/admin',
'domain' => 'example.com',
'secure' => true,
'httponly' => true
]);
获取 Cookie
// 基本获取
$userId = Cookie::get('user_id');
// 获取并指定默认值
$theme = Cookie::get('theme', ['default' => 'light']);
// 获取并转换类型
$userId = Cookie::get('user_id', ['type' => 'int']);
$isRemembered = Cookie::get('remember', ['type' => 'bool']);
// 获取并进行函数处理
$username = Cookie::get('username', ['function' => 'trim']);
// 组合多个选项
$limit = Cookie::get('page_limit', [
'default' => 10,
'type' => 'int',
'function' => 'abs' // 确保是正数
]);
检查与删除 Cookie
// 检查 Cookie 是否存在
if (Cookie::has('user_id')) {
echo '用户Cookie已设置';
}
// 基本删除
Cookie::delete('temp_cookie');
// 指定路径和域名删除
Cookie::delete('auth_token', [
'path' => '/admin',
'domain' => 'example.com'
]);
批量操作
// 获取所有 Cookie(不带前缀)
$allCookies = Cookie::all();
foreach ($allCookies as $key => $value) {
echo "{$key}: {$value}";
}
// 获取所有 Cookie(带前缀)
$allWithPrefix = Cookie::all(true);
高级用法
Cookie 前缀管理
// 配置文件中设置前缀
// 'cookie_prefix' => 'myapp_'
// 使用时自动添加前缀
Cookie::set('user_id', 100); // 实际存储为 'myapp_user_id'
// 获取时无需指定前缀
$userId = Cookie::get('user_id'); // 自动查找 'myapp_user_id'
值处理与过滤
// 获取 Cookie 并应用多个处理函数
$search = Cookie::get('last_search', [
'function' => ['trim', 'htmlspecialchars'],
'default' => ''
]);
// 禁用 HTML 特殊字符过滤
$rawValue = Cookie::get('raw_data', [
'filter' => false
]);
// 设置数字限制
$pages = Cookie::get('history_pages', [
'type' => 'int',
'function' => 'min:,20' // 限制最大值为20
]);
跨子域共享 Cookie
// 设置可在子域间共享的 Cookie
Cookie::set('shared_data', 'value', [
'domain' => '.example.com', // 注意前导点
'path' => '/',
'expire' => time() + 86400
]);
说明
- 安全建议对敏感数据使用 httponly => true 防止 JavaScript 访问在 HTTPS 环境中使用 secure => true 确保加密传输避免在 Cookie 中存储大量数据,建议控制在 4KB 以内
- 前缀使用所有方法自动应用配置中的 cookie_prefix 前缀使用 all(false) 获取无前缀的 Cookie 键值对
- 过期时间expire 参数应为 Unix 时间戳,非相对秒数默认为 0,表示浏览器关闭后过期(会话 Cookie)
- 值处理get() 方法通过 Http::handling() 处理返回值支持类型转换、默认值和函数处理
- 操作结果set() 和 delete() 方法返回布尔值,表示操作是否成功检查返回值可判断 Cookie 操作是否有效
通过合理使用 Cookie 类提供的方法,可以简化 Cookie 管理,提高安全性,并与框架其他组件保持一致的使用体验。