0

I want to use header() function to set a cookie with 30 day expiry time as shown below:

$exptime=time()+30*24*60*60;
header("Set-Cookie: __try1=usingheader; expires=$exptime; path=/");

But this doesn't work and just sets a session cookie. The same thing works fine with setcookie() function

setcookie("__try2", "usingsetcookie", $exptime, '/');

The response headers are as below:

Set-Cookie: __try1=usingheader; expires=1613126399; path=/
Set-Cookie: __try2=usingsetcookie; expires=Fri, 12-Feb-2021 10:39:59 GMT; Max-Age=2592000; path=/

Would appreciate any help on this.

  • Does this answer your question? [set-cookie expiration in seconds](https://stackoverflow.com/questions/13456820/set-cookie-expiration-in-seconds) – Ivar Jan 13 '21 at 11:00
  • What **exactly** do you mean by "a session cookie"? – Nico Haase Jan 13 '21 at 13:10
  • 2
    @NicoHaase [A cookie that is removed when the client shuts down](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#session_cookie). – Ivar Jan 13 '21 at 13:15
  • 1
    @Ivar Thank you for your suggestion, it did answer my question. Looks like there is another way to do it (since php v5.1.1 using DATE_COOKIE). I will update it as an answer here in case anyone finds it useful in future. – applecodervinegar Jan 19 '21 at 11:30

1 Answers1

2

The proper time format for the expires flag is something like this Tue, 19 Jan 2021 15:40:59 GMT. We can generate this format using gmdate(). Below is an example to set the expiry time to 6 months from the current time.

$expirytime = gmdate("D, d-M-Y H:i:s T", strtotime( '+6 months' ));

or since PHP 5.1.1 we can use the below. See reference.

echo gmdate(DATE_COOKIE , strtotime( '+6 months' ));