Set a cookie to never expire Set a cookie to never expire php php

Set a cookie to never expire


All cookies expire as per the cookie specification, so this is not a PHP limitation.

Use a far future date. For example, set a cookie that expires in ten years:

setcookie(  "CookieName",  "CookieValue",  time() + (10 * 365 * 24 * 60 * 60));

Note that if you set a date past 2038 in 32-bit PHP, the number will wrap around and you'll get a cookie that expires instantly.


Maximum value: 2147483647

setcookie("CookieName", "CookieValue", 2147483647);

To avoid integer overflow the timestamp should be set to:

2^31 - 1 = 2147483647 = 2038-01-19 04:14:07

Setting a higher value might cause problems with older browsers.

Also see the RFC about cookies:

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.

and RFC 2616, 14.6 Age:

If a cache receives a value larger than the largest positive integer it can represent, or if any of its age calculations overflows, it MUST transmit an Age header with a value of 2147483648 (2^31).

http://www.faqs.org/rfcs/rfc2616.html


Set a far future absolute time:

setcookie("CookieName", "CookieValue", 2147483647);

It is better to use an absolute time than calculating it relative to the present as recommended in the accepted answer.

The maximum value compatible with 32 bits systems is:

2147483647 = 2^31 = ~year 2038