user979331
user979331

Reputation: 11871

PHP cookie time format not working

I have these two cookies and they do work but only if the cookies expiry is 5 hours and over, nothing under. If I set the cookie expiry to 0 it will also work, but I what I need to a cookie to expire in 2 hours. It works in firefox when I set the cookie to expire in 2 hours, but not in Chrome or IE.

I only see the browser (Chrome) get the cookie if the expiry is from five hours from now or more. or if the expiry is set to 0. What am I doing wrong?

setcookie('expire', 'test', time() + 7200, "/");

I dont why the time function is not working so my cookie will expire in two hours.

Any help would be appreciated.

Upvotes: 4

Views: 5293

Answers (2)

Bryan Agee
Bryan Agee

Reputation: 5052

So--are you in the Central or Eastern US timezone? More than likely, your time stamp is being interpreted as UTC, and therefore only working when you go over the offset. Safer to use a format like phpdate's C or R:

$date = new Datetime('+2 hours');
setcookie('expire', 'test', $date->format('C'), "/");

or even better, use the predefined cookie date format:

setcookie('expire', 'test', $date->format(DateTime::COOKIE), "/");

These include the offset in the string, so that the browser can't screw it up. Also, it makes for much easier troubleshooting when looking at the response headers, since it is in a human readable format.

Upvotes: 11

Mansfield
Mansfield

Reputation: 15150

If you're doing this on a server, double check that the time on the development server is correct - I know I had an issue exactly like this and a wonky server time ended up being the culprit.

Upvotes: 0

Related Questions