Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get cookie's expire time

Tags:

php

cookies

When I create a cookie, how to get cookie's expire time?

like image 301
love Avatar asked Nov 17 '10 09:11

love


People also ask

Which cookie has no expire time?

A cookie with no expiration date specified will expire when the browser is closed. These are often called session cookies because they are removed after the browser session ends (when the browser is closed).

How do you set cookies to expire in 30 days?

time()+60*60*24*30 will set the cookie to expire in 30 days. If not set, the cookie will expire at the end of the session (when the browser closes). The path on the server in which the cookie will be available on.


2 Answers

Putting an encoded json inside the cookie is my favorite method, to get properly formated data out of a cookie. Try that:

$expiry = time() + 12345; $data = (object) array( "value1" => "just for fun", "value2" => "i'll save whatever I want here" ); $cookieData = (object) array( "data" => $data, "expiry" => $expiry ); setcookie( "cookiename", json_encode( $cookieData ), $expiry ); 

then when you get your cookie next time:

$cookie = json_decode( $_COOKIE[ "cookiename" ] ); 

you can simply extract the expiry time, which was inserted as data inside the cookie itself..

$expiry = $cookie->expiry; 

and additionally the data which will come out as a usable object :)

$data = $cookie->data; $value1 = $cookie->data->value1; 

etc. I find that to be a much neater way to use cookies, because you can nest as many small objects within other objects as you wish!

like image 182
Braikar Avatar answered Sep 23 '22 03:09

Braikar


This is difficult to achieve, but the cookie expiration date can be set in another cookie. This cookie can then be read later to get the expiration date. Maybe there is a better way, but this is one of the methods to solve your problem.

like image 42
Thariama Avatar answered Sep 22 '22 03:09

Thariama