10

I need to set cookie that expires after 1 hour using PHP setcookie function. Timezone on my server is set to GMT. How should I set cookie expiry date, to make it working across different client's browser timezones?

Karol
  • 7,803
  • 9
  • 49
  • 67
  • 1
    @DonCallisto he may haven't got the answer he needed on most of his questions. – noob Apr 19 '12 at 13:15
  • Thanks guys, both comments are useful. Indeed I haven't got answers I needed, but it's good to remember about it. – Karol Apr 19 '12 at 13:49
  • 1
    You might find [`$cookie->setExpiryTime($expiryTime)`](https://github.com/delight-im/PHP-Cookie/blob/004cde69ec840e65c15275e09b92ecb1da06f357/src/Cookie.php#L80) or [`$cookie->setMaxAge($maxAge)`](https://github.com/delight-im/PHP-Cookie/blob/004cde69ec840e65c15275e09b92ecb1da06f357/src/Cookie.php#L92) helpful, as found in [this standalone library](https://github.com/delight-im/PHP-Cookie). – caw Sep 21 '16 at 02:43

4 Answers4

9

Near as I can tell it shouldn't matter what the client time is. PHP sets the expire time based on the unix timecode. Any variation in that time should reside with the server.

Here is the excerpt from the PHP manual for setcookie():

expire:

The time the cookie expires. This is a Unix timestamp so is in number of seconds since the epoch. In other words, you'll most likely set this with the time() function plus the number of seconds before you want it to expire. Or you might use mktime(). time()+60*60*24*30 will set the cookie to expire in 30 days. If set to 0, or omitted, the cookie will expire at the end of the session (when the browser closes).

robsch
  • 9,358
  • 9
  • 63
  • 104
RockyFord
  • 8,529
  • 1
  • 15
  • 21
6

PHP's setcookie() function accepts an integer corresponding to a Unix timestamp value. If your cookie should have a 1 hour time to live, you could just use time() + 3600 for that value. PHP will then create a cookie with expire time like "expires=Fri, 3 Aug 2001 20:47:11 UTC". It is in UTC (GMT) so you do not have to worry about the timezone of the client browser

kDjakman
  • 116
  • 5
0

You could try with getTimeZone and setTimeZone Take a look here

Also strtotime seems to be fine for retrive the correct format of datetime, then you could use gmdate for convert it

DonCallisto
  • 29,419
  • 9
  • 72
  • 100
0

Well suppose you use set cookie.

I may be wrong but i think:

You provide the expire parameter as a Unix timestamp, and you calculate the timestamp as "in an hour", so you want the cookie to expire in an hour. So don't care about timezone as the unix timestamp is unambiguous.

Then task of the browser is to translate the unix timestamp in a date based on bowser settings (locale, language and so on)

ab_dev86
  • 1,952
  • 16
  • 21