简体   繁体   中英

PHP Cookie set expiry time to none

I am setting a cookie, but having some issue. Currently the cookie format is this:

setcookie("company_id", $company_id, 0, '/');

So expiry time is set to 0 means cookie will never expire, but when I tried to not to set any expiry time so I passes an empty argument in the third parameter like this:

setcookie("company_id", $_POST["company_id"], "", '/');

But this is not working, cookie is not getting, when I changed the empty argument to 0 it than start working. Any suggestions?

The expire parameter is in seconds. Setcookie function

All the arguments except the name argument are optional. You may also replace an argument with an empty string ("") in order to skip that argument. Because the expire argument is integer, it cannot be skipped with an empty string, use a zero (0) instead.

So unless you want it to expire at the end of the session you will need to have a value other than zero.

0 suggests the cookie should expire at the end of the session, if you want it to 'never expire'use a really long time.

setcookie("TestCookie", $value, time()+3600*24*365*10, '/')

Eg that would be ten years.

Bear in mind people can clear cookies often. So yours may get deleted. Cookies are also browser specific, so if the data that is stored in this, is needed every-time, then if the user switches browser this will no longer be available unless you set it again.

You're asking the wrong question. There is no way to set a cookie to not expire; This is not a PHP limitation, it's just not part of the specification for cookies (http://www.faqs.org/rfcs/rfc2965.html).

Your best bet is to use a date far in the future. For example, to set a cookie that expires in twenty years:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM