简体   繁体   中英

PHP - Setting Cookie Expire + Time

A cookie isn't being set on my computer. It works locally but not live. I only want the cookie to exist for 20 minutes. The only reason I can think of that it won't work is because the server is in the states. I am x hours ahead. Thus the cookie set time is already expired. Is this correct?

setcookie($cookiename, $cookie, time() + 1200);

If the server time is 6am and my time is 12pm. Would the cookie be set to expire at 6:20am or 12:20pm?

If it is the former, how do I set the cookie expiry time based on the users local time? If it is the later I will do some more trouble shooting on Monday.

I've had a similar problem in the past, the advice I was always given is to make sure cookies (if set in different time zones) have an expiration of a minimum of 25 hours. This enables anyone anywhere to utilise the cookie. In alot of cases an invalid cookie = no access = a big deal.

Modern computing has made reservations for this, and synchronised time will make sure cookies are always set in the users local time. That said, exceptions are still to be found.

20 minutes is a very short time to enable a cookie, consider increasing it. If the cookie is still not set locally, I would assume your browser has blocked incoming cookies from the server.

The time() function will get the server time, but I believe Cookies use GMT time.

Easiest way to get the GM time from PHP is to use:

<?php
  $gmtime = gmdate('U');
?>

So you'd set the cookie like this:

setcookie($cookiename, $cookie, gmdate('U') + 1200);

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