16

I'm trying to set a PHP cookie to expire 1 Year from when the user logged in, and I'm doing it this way:

setcookie("myCookie",'exampleUserName',(365 * 24 * 60) ,'/');

The problem is, when I view the cookie using the console in Chrome or Firefox, it show Expires Sun, 05, 2014 in Chrome and Expires = Session in Firefox.

Any other site like Google or stackoverflows cookies show the correct expiration date.

How can I set this right?

1
  • 4
    Your 365 * 24 * 60 is missing a factor of 60 and must be added to time(), it's as simple as that.
    – caw
    Sep 21, 2016 at 4:24

6 Answers 6

52
setcookie($cookie_name, $cookie_value, strtotime("+1 year"));
1
  • 1
    I have had this method for years but it has stopped working since a year back or so. Jan 24, 2019 at 2:53
40

Do like this...

setcookie("myCookie",'exampleUserName',time()+31556926 ,'/');// where 31556926 is total seconds for a year.
1
  • 1
    I got wrong expire date results using this code and not every year has 31556926 seconds, leap years for example. Nov 29, 2019 at 5:55
6

try this one

setcookie($cookie_name, $cookie_value, time() + ( 365 * 24 * 60 * 60));
2

The third param is the time in future that mean time() + time in seconds. Your 365 * 24 * 60 means 1971 ( 1970 + 1 ), this is in the past. Cookie in past will not be used - people set cookie to the past time to clear cookie. Do exactly like Shankar.

2

Try this:

<?php
       setcookie("TestName", "Test Value", time()+3600 * 24 * 365);
?>

>> Here 'TestName' is name of cookie.
>> "Test Value" is value to store.
>> time()+3600 * 24 * 365 - will set cookie time till 1 year.

Thanks!

0

don't complacate it

just do one thing

there are 86400 secound in a day so just multiply

here is an example of 30 days

setcookie("test","value",time() + (86400 * 30));

generaliz it like (86400 * days)

setcookie("test","value",time() +(86400 * 365));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.