Home > Backend Development > PHP Tutorial > How Can I Create a Persistent Cookie in PHP Without an Expiration Date?

How Can I Create a Persistent Cookie in PHP Without an Expiration Date?

Linda Hamilton
Release: 2024-12-02 12:36:15
Original
808 people have browsed it

How Can I Create a Persistent Cookie in PHP Without an Expiration Date?

Extended Cookie Expiration for Persistent Sessions

The requirement to set a cookie to never expire arises frequently when developing web applications that require persistent user sessions. However, the PHP documentation suggests setting an expiration date for cookies. While you can set a cookie to expire at the end of the session or in the future, you may wonder if there's a way to make a cookie last indefinitely.

Cookie Expiration Limitation

Unfortunately, all cookies have an expiration period as per the cookie specification. This expiration is not a PHP limitation but a fundamental property of cookies.

Approximating Never Expiration

To simulate a never-expiring cookie, you can set a distant future date as the expiration time. For instance, you could set a cookie to expire in ten years:

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

This approach effectively extends the cookie's lifespan beyond the user's typical session or device usage timeframe.

32-Bit PHP Limitation

Note that for 32-bit PHP, setting an expiration date past 2038 can result in a wrap-around effect, effectively causing the cookie to expire immediately.

Browser Limitations

In 2023, web browsers have started to enforce a maximum expiration date for cookies. As of Chrome release M104, cookies can no longer have an expiration date more than 400 days in the future.

The above is the detailed content of How Can I Create a Persistent Cookie in PHP Without an Expiration Date?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template