Search code examples
phpcookies

Set a cookie to never expire


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?


Solution

  • 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.