Cookie 的读写封装,自动处理前缀、过期时间、域名与 HttpOnly 等参数,参数统一在 config/app.php。
配置
'cookies_prefix' => 'hz_',
'cookies_outtime' => 0, // 0 = 浏览器关闭即失效
'cookies_path' => '/',
'cookies_domain' => '',
'cookies_secure' => false, // 只走 HTTPS
'cookies_httponly' => true,
读写
use houze\Cookie;
Cookie::set('theme', 'dark', 86400); // 名称 / 值 / 有效期(秒)
Cookie::get('theme'); // 不存在返回 null
Cookie::has('theme');
Cookie::delete('theme');
Cookie::clear(); // 清空全部
// set 的完整签名:set($name, $value, $expire, $path, $domain, $secure, $httponly)
前缀是自动加的
Cookie::set('theme', 'dark');
// 浏览器里看到的是 hz_theme
// 读取时用 'theme' 即可,不用自己拼前缀
安全建议
- 存登录态的 Cookie 一定
httponly = true,否则 XSS 直接偷走; - 上 HTTPS 后把
secure打开; - 不要把「是否登录」只写在 Cookie 里——Cookie 可被伪造,判断要回服务端查;
- 中间件里统一鉴权,别在每个方法里各写一遍。