查看关于设置cookie的php文档,我看到我可以设置cookie的过期日期.您可以将cookie设置为在浏览器会话结束时或将来的某个时间到期,但我没有看到将cookie设置为永不过期的方法.这是否可能,这是如何实现的?
Joe*_*ckx 245
所有cookie都根据cookie规范到期,因此这不是PHP限制.
使用远期日期.例如,设置一个在十年后到期的cookie:
setcookie(
"CookieName",
"CookieValue",
time() + (10 * 365 * 24 * 60 * 60)
);
Run Code Online (Sandbox Code Playgroud)
请注意,如果您在PHP中设置了一个超过2038的日期,那么该数字将会回滚,您将获得一个即时过期的cookie.
PiT*_*ber 69
最大值:2147483647
setcookie("CookieName", "CookieValue", 2147483647);
Run Code Online (Sandbox Code Playgroud)
为避免整数溢出,时间戳应设置为:
2^31 - 1 = 2147483647 = 2038-01-19 04:14:07
Run Code Online (Sandbox Code Playgroud)
设置较高的值可能会导致旧浏览器出现问题.
Run Code Online (Sandbox Code Playgroud)Max-Age=value OPTIONAL. The value of the Max-Age attribute is delta-seconds, the lifetime of the cookie in seconds, a decimal non-negative integer. To handle cached cookies correctly, a client SHOULD calculate the age of the cookie according to the age calculation rules in the HTTP/1.1 specification [RFC2616]. When the age is greater than delta-seconds seconds, the client SHOULD discard the cookie. A value of zero means the cookie SHOULD be discarded immediately.
如果缓存接收的值大于它可以表示的最大正整数,或者如果其任何年龄计算溢出,它必须发送一个值为2147483648(2 ^ 31)的Age头.
http://www.faqs.org/rfcs/rfc2616.html
Dav*_*vid 35
设定一个遥远的未来绝对时间:
setcookie("CookieName", "CookieValue", 2147483647);
Run Code Online (Sandbox Code Playgroud)
最好使用绝对时间,而不是按照接受的答案中的建议计算相对于现在的时间.
与32位系统兼容的最大值是:
2147483647 = 2^31 = ~year 2038
Run Code Online (Sandbox Code Playgroud)
Joh*_*ohn 13
我的特权阻止我在第一篇文章上发表评论,所以它必须要到这里.
从当前日期开始提前20年设置时,应考虑2038 unix bug,这是上述正确答案.
你的cookie在2018年1月19日+(20年)可能会遇到2038问题,具体取决于你最终运行的浏览器和/或版本.
小智 7
难道你不能说一个永无止境的循环,cookie到期为当前日期+ 1所以它永远不会达到它应该到期的日期,因为它总是明天?有点矫枉过正,但只是说.
虽然这不太可能,你可以做类似于谷歌的事情,并将你的cookie设置为在2038年1月17日到期之前到期.
实际上,你可能最好将你的cookie设置为10年或60*60*24*365*10,这应该比你的cookie所使用的大多数机器都要长.
| 归档时间: |
|
| 查看次数: |
234056 次 |
| 最近记录: |