note 19426 deleted from function.setcookie by sniper
| From: | sniper@php.net | Date: | Wed, 11 Dec 2002 07:18:28 +0000 |
| Subject: | note 19426 deleted from function.setcookie by sniper | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-40735@lists.php.net to get a copy of this message | ||
For all those people that are having issues with setting a cookie to live for a certain time period.
Here is a possible solution that does not rely on the different browser implementations and local
time settings.
Simply store the creation time along with the value of the cookie. This will then always rely on the
servers clock settings(which presumably shouldn't change).
The only drawback to this approach is that the client will have a cookie that won't expire,
unless you explicitly delete it. e.g.
if(empty($HTTP_COOKIE_VARS['cookie_name'])) {
// set cookie and store the creation time within the value of the cookie
setcookie("cookie_name", "cookie value"."|".time(), 31536000);
} else {
// check if cookie has expired, if so delete it
$cookie_life = 3600;
$tok = explode("|", $HTTP_COOKIE_VARS["cookie_name"]);
$cookie_value = $tok[0];
$creation_time = $tok[1];
if((time()-$creation_time) > $cookie_life) {
// cookie has expired so delete it.
setcookie("cookie_name", "");
}
}
I haven't tested this on different systems, but would be quite interested to see which it
wouldn't work on (some people have said that all arguments must be passed to setcookie except
for secure flag).
This is of course a very simple example and people should adapt it to their needs.
All comments and feedback is welcome.
Brendan