Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP cookie time format not working

Tags:

php

cookies

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.

like image 1000
user979331 Avatar asked Dec 28 '22 02:12

user979331


1 Answers

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.

like image 165
Bryan Agee Avatar answered Jan 09 '23 01:01

Bryan Agee