Cookies expiring in different timezones

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
ben.artiss
Forum Contributor
Posts: 116
Joined: Fri Jan 23, 2009 3:04 pm

Cookies expiring in different timezones

Post by ben.artiss »

Hi everyone,

I'm getting a bit confused about how cookies work in different timezones and wondered if someone could shed some light? I'm using a now() function like CodeIgniter's that works out the current timestamp in GMT:

Code: Select all

$now = time();
$time = mktime(gmdate('H', $now), gmdate('i', $now), gmdate('s', $now), gmdate('m', $now), gmdate('d', $now), gmdate('Y', $now));
And I'll be setting cookies based on this time:

Code: Select all

$now    = now();       // 2011-09-11 18:00:00 UTC
$expire = $now + 3600; // 2011-09-11 19:00:00 UTC
setcookie('cookie_name', 'cookie_value', $expire);
If the server sets it to expire on 2011-09-11 19:00:00 (UTC), and let's say the user is UTC-2, will the user's browser interpret the expire time as 2011-09-11 19:00:00 or 2011-09-11 17:00:00? In other words, will they be getting sent before/after they should? I'm hoping the browser will be able to work it out but before I code away I just thought I'd check.

Thanks in advance.

P.S. Apologies if this is the wrong place for the question! I'm not sure if this counts as theory / design ..
greip
Forum Commoner
Posts: 39
Joined: Tue Aug 23, 2011 8:23 am
Location: Oslo, Norway

Re: Cookies expiring in different timezones

Post by greip »

You send the Expires time using GMT time zone. The browser will know the difference between GMT and the local time zone and expire the cookie at the right time. Some relevant information here: http://en.wikipedia.org/wiki/HTTP_cooki ... nd_Max-Age
ben.artiss
Forum Contributor
Posts: 116
Joined: Fri Jan 23, 2009 3:04 pm

Re: Cookies expiring in different timezones

Post by ben.artiss »

Excellent, thanks for that greip.

I noticed something while I was testing time(), mktime() and gmmktime() which I found a little strange too. It seems (regardless of server timezone) mktime was an hour behind gmmktime:

Code: Select all

$now = time();
$H = gmdate("H", $now);
$i = gmdate("i", $now);
$s = gmdate("s", $now);
$m = gmdate("m", $now);
$d = gmdate("d", $now);
$Y = gmdate("Y", $now);

$mktime = mktime($H, $i, $s, $m, $d, $Y);
$gmtime = gmmktime($H, $i, $s, $m, $d, $Y);

echo date('Y-m-d H:i:s', $mktime); // 2011-09-18 11:09:46
echo date('Y-m-d H:i:s', $gmtime); // 2011-09-18 12:09:46
Did I miss something? For some reason I assumed they'd be the same..
Post Reply