Set a cookie to never expire
Asked Answered
W

14

244

Looking at the php documentation on setting a cookie I see that I can set an expiration date for the cookie. You can set the cookie to expire at the end of the browser session or at some time in the future but I do not see a way to set the cookie to never expire. Is this even possible and how is this accomplished?

Willis answered 20/7, 2010 at 13:29 Comment(3)
@sAc: Why is this a bad thing?Willis
Because that is not possible anyway as per the cookie specification. It can not be set to never expire.Siloxane
You may use $cookie->setMaxAge(2147483647);, which is later than 2080 and works on both 32-bit and 64-bit, with github.com/delight-im/PHP-CookieMacswan
Z
315

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.

Edit: As in 2023, obeying the max depends on the web browsers. As of Chrome release M104 (August 2022) cookies can no longer set an expiration date of more than 400 days in the future.

Zipnick answered 20/7, 2010 at 13:35 Comment(21)
Agreed! And I think, that in 20 years, websites will be far ahead, that possibly no cookies will be used.. @brainimus: Just use the oldschool system everyone mentioned - current time + time in far future!Friedrich
Beware that when 2018 comes around, if we're not using 64-bit PHP, that this will wrap around the 32-bit integer and get sent to the client as a time near zero. (This is happening right now for 25-year cookies on PHP.)Inguinal
A bit short, I think. Could also just set the max date, but then you'd have to make sure you're not running the app anymore by then.Zipnick
Well 10 years is not a long time ;-) See David's answer.Disject
Will be funny to come back to these comments in 2018 (just 5 years away now) and see as everyone scramble to implement the Y2018 upgrade then again 20 years later in 2038. Hopefully we all make the jump to 64-bit everything by then this won't be a problem for another 292 billion years on Sunday, 4 December 292,277,026,596. Unless we reach a singularity before I die I don't think I'll have to worry about that one.Lenard
If a person is using the same computer at the end of 2037 that they are using now... that would just be sad!Pew
You could always set the expiration time directly with a raw HTTP header: header('Set-Cookie: cookie_name=cookie_value; expires=Fri, 31-Dec-9999 23:59:59 GMT');. Unless the PHP devs decides to finally make setcookie utilize 64-bit integers for the timestamp value (64-bit POSIX timestamps can be generated with e.g. date_create('+1000 years')->format('U'), even on 32-bit PHP), it might be up to ourselves to write custom setcookie functions in our applications..Outguess
You can make it infinite by giving them a new cookie on their next visitOla
@Ola But what if they come back after 10 years?Rearmost
@Lenard Hello from the future. Just one more year to 2018... I think most people use 64 bit php now....Fart
@Fart thanks for the update, yeah I think really most developers back then were working with 64 bit hardware but not sure what the actual OS and packages were that were most widely distributed (or current stats for that matter) but seems like disaster averted..... for now (honestly somewhat surprising how well PHP has managed to survive and evolve to this point).Lenard
Why? What's with 2038?Cephalometer
Expires=Tue, 19 Jan 2038 03:14:07 GMTFlagon
I'm reading this in 2018, panicked for a moment, then realized I was ok.Hapsburg
Tomorrow it's gonna be 2019 and I'm implementing cookies on my website rather than eating some during the celebrations.Magdala
Hello fellow time-travelers, I'm speaking to you from far into 2019. Our planet has changed a lot. We're seeking for places among the universe to save our species. In the meanwhile we still use cookies.Demulcent
Any updates on whether this caused some headaches for people in 2018? ;)Fibrillation
Speaking from Late 2021, the flow of time is still.... well.. flowing.Shannanshannen
Reading this from my neuralink in 2947. We still use cookies, but they're now called numnums.Decapolis
Lol like people will still even be using cookies in 2018...Ubiquitous
i am from 2022 and the world still using cookie ;)Stanford
M
117

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

Mikaelamikal answered 18/3, 2014 at 12:30 Comment(1)
Very thorough! Thank you for the good references.Individualize
K
44

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
Karly answered 27/7, 2012 at 9:45 Comment(2)
2 billions is easy to remember but the ideal number for $forever would be 2^31 - 1 = 2147483647 corresponding to January 2038. It is the maximum value to avoid the integer overflow of the 2038 bug as @John said.Karly
Looking back in 2023, is there a site to check the market share (the real usage) of 32-bit hardwares? Since, 2038 is approaching, and even IE is deprecating! I now kinda double if anyone would still use such old computer or new IoT device (which usually are 32-bit) to surf the web. But I know many labs and hospitals still have old PCs connected to internet, though user are warned to not use the network-related funcUnbalance
T
17

My privilege prevents me making my comment on the first post so it will have to go here.

Consideration should be taken into account of 2038 unix bug when setting 20 years in advance from the current date which is suggest as the correct answer above.

Your cookie on January 19, 2018 + (20 years) could well hit 2038 problem depending on the browser and or versions you end up running on.

Thirteen answered 26/6, 2012 at 18:44 Comment(0)
A
6

Can't you just say a never ending loop, cookie expires as current date + 1 so it never hits the date it's supposed to expire on because it's always tomorrow? A bit overkill but just saying.

Armored answered 28/8, 2012 at 23:10 Comment(2)
Actually, he has a point. Just using some suitable 'inactivity period' of, say, 3 months and then refreshing the cookie with that period on each request does make some sense.Chatham
@StijndeWitt Or just 10 years. Then update it if the user visits within 10 years...Rearmost
D
6

As of whenever the link here was posted, Chrome cookies can, at max, live as long as 400 days. Chrome is a big deal at the time of this response, so I would make a cookie's expiration be in 400 days or less.

If you don't want to click on the link, it says, in summary:

When cookies are set with an explicit Expires/Max-Age attribute the value will now be capped to no more than 400 days in the future. Previously, there was no limit and cookies could expire as much as multiple millennia in the future.

Dacoity answered 30/9, 2022 at 21:7 Comment(1)
Yeah, as of late 2022 the best answer to this question has basically changed to "just set it to 400 days" if you want it to last as long as possible. Although there is no harm in setting it longer as the browser will just reduce it to this anyway. But also, it's more important to address the issue of refreshing cookies now too, as having everyone auto logged out after just over a year even when they are constantly using a website is not a desired behaviour!Tilley
N
5

While that isn't exactly possible you could do something similar to what Google does and set your cookie to expire Jan 17, 2038 or something equally far off.

In all practicality you might be better off setting your cookie for 10 years or 60*60*24*365*10, which should outlive most of the machines your cookie will live on.

Negress answered 20/7, 2010 at 13:41 Comment(2)
That will work until early 2028, at which point you'll overflow the value and the cookies will stop working. Better to use an absolute value instead.Champerty
Assuming his code will still be running on outdated machines in 2028... Somehow I am more worried that everyone will forget to update the fixed date... Software tends to outlive hardware.Chatham
B
4

If you want to persist data on the client machine permanently -or at least until browser cache is emptied completely, use Javascript local storage:

https://developer.mozilla.org/en-US/docs/DOM/Storage#localStorage

Do not use session storage, as it will be cleared just like a cookie with a maximum age of Zero.

Baluster answered 14/11, 2012 at 9:37 Comment(1)
Cant consider localStorage when it comes to reading server-side data.Hippocrene
Z
3

Never and forever are two words that I avoid using due to the unpredictability of life.

The latest time since 1 January 1970 that can be stored using a signed 32-bit integer is 03:14:07 on Tuesday, 19 January 2038 (231-1 = 2,147,483,647 seconds after 1 January 1970). This limitation is known as the Year 2038 problem

setCookie("name", "value", strtotime("2038-01-19 03:14:07"));
Zabrina answered 3/5, 2020 at 22:50 Comment(0)
S
1

You shouldn't do that and that's not possible anyway, If you want you can set a greater value such as 10 years ahead.

By the way, I have never seen a cookie with such requirement :)

Siloxane answered 20/7, 2010 at 13:34 Comment(2)
I would assume cookies for uniquely answered polls that don't want to bother too much with preventing multiple entries have this requirement.Recline
look @sarfraz its the computer cookie not the ones you eat.Christmas
S
1

You can set a far date from the date, the cookie is created like this:

var Cookie_expiry = new Date();
Cookie_expiry.setDate(Cookie_expiry.getDate()+10e5);   
// expiry date of cookie is set to be practically infinite (~ 4000 years)
setCookie('token', 'token_value', {expires: Cookie_expiry});
Suprarenal answered 2/10, 2021 at 4:27 Comment(0)
C
0

I believe that there isn't a way to make a cookie last forever, but you just need to set it to expire far into the future, such as the year 2100.

Coinage answered 20/7, 2010 at 13:32 Comment(0)
L
-1

I'm not sure but aren't cookies deleted at browser close? I somehow did a never expiring cookie and chrome recognized expired date as "at browser close" ...

Latarsha answered 20/10, 2011 at 19:0 Comment(1)
Not necessarily, if you set an expiration date on the cookie, it will survive after you close your browser and re-open it. If you do not set an expiration, the default behavior will be to be deleted when you close your browser.Laterite
D
-2

You can't but what if you set expire time to now + 100 years ?

Dour answered 20/7, 2010 at 13:32 Comment(1)
No, because that would exceed the maximum value in January 2038.Champerty

© 2022 - 2024 — McMap. All rights reserved.