setcookie如何设置过期时间?一共有多少种形式的写法?底层原理是什么?
·
一、setcookie() 设置过期时间的 3 种核心方法
1. 相对时间写法(推荐)
使用 strtotime() 函数将自然语言时间转换为 Unix 时间戳:
// 示例:1天后过期
setcookie('user', 'John', time() + 86400); // 86400秒 = 1天
// 更直观的写法(推荐)
setcookie('user', 'John', strtotime('+1 day'));
// 其他常见格式:
strtotime('+30 minutes'); // 30分钟后
strtotime('next Monday'); // 下周一
strtotime('2024-12-31 23:59:59'); // 指定日期
2. 绝对时间戳写法
直接使用 Unix 时间戳(秒级):
// 示例:2025年1月1日 00:00:00 过期
$expireTime = mktime(0, 0, 0, 1, 1, 2025);
setcookie('theme', 'dark', $expireTime);
3. 会话级 Cookie(浏览器关闭后失效)
将过期时间设为 0 或省略参数:
setcookie('session_id', 'abc123', 0); // 浏览器关闭后失效
// 或
setcookie('session_id', 'abc123'); // 效果相同
二、底层原理
1. HTTP 协议层面
当 PHP 执行 setcookie() 时,会生成一个 Set-Cookie 响应头,例如:
Set-Cookie: user=John; expires=Wed, 01-Jan-2025 00:00:00 GMT; path=/
expires:浏览器用 GMT 时间 表示过期时间(底层自动转换 Unix 时间戳为 GMT 字符串)。- 存储机制:浏览器根据
expires决定是否将 Cookie 持久化到磁盘:- 如果设置过期时间 → 存储到磁盘(长期有效)。
- 如果未设置或设为
0→ 仅存内存(会话级 Cookie)。
2. PHP 函数的实现
setcookie() 的第三个参数 $expires 本质是 Unix 时间戳:
bool setcookie(
string $name,
string $value = "",
int $expires = 0,
string $path = "",
string $domain = "",
bool $secure = false,
bool $httponly = false
)
$expires = 0:等价于会话级 Cookie(浏览器关闭失效)。$expires > 0:浏览器会将 Cookie 保存到本地,直到过期。
三、完整示例代码
场景:设置 7 天免登录
// 生成用户令牌
$token = bin2hex(random_bytes(32));
// 设置 Cookie(7天后过期)
setcookie(
'auth_token',
$token,
strtotime('+7 days'), // 过期时间
'/', // 全站生效
'example.com', // 域名
true, // 仅 HTTPS
true // 禁止 JS 访问(防 XSS)
);
// 通过 $_COOKIE 读取(需刷新页面后生效)
if (isset($_COOKIE['auth_token'])) {
echo "您的登录令牌:" . $_COOKIE['auth_token'];
}
四、注意事项
1. 时区问题
strtotime()依赖 PHP 时区设置,确保php.ini中date.timezone正确:
date_default_timezone_set('Asia/Shanghai'); // 手动设置时区
2. 浏览器兼容性
- 所有现代浏览器均支持 Unix 时间戳转 GMT 格式,但需确保服务器时间准确。
3. 删除 Cookie
设置过期时间为过去的时间戳即可删除:
setcookie('user', '', time() - 3600); // 1小时前
五、时间格式对比表
| 写法 | 示例值(假设当前为 2024-01-01 12:00:00) | 适用场景 |
|---|---|---|
strtotime('+1 day') | 2024-01-02 12:00:00 | 相对时间(推荐) |
time() + 3600 | 2024-01-01 13:00:00 | 精确秒数控制 |
mktime(0,0,0,1,1,2025) | 2025-01-01 00:00:00 | 绝对时间 |
0 | 会话级 Cookie | 临时数据 |
通过以上方法,可以灵活控制 Cookie 的生命周期,适应不同业务需求。
更多推荐


所有评论(0)