UZSTYLE GROUP
UZSTYLE GROUP

Reputation: 65

Update a cookie value without changing its expiry date?

Update a cookie value without changing its expiry date?

$c = $_COOKIE["count"];
$c++;
if (isset($_COOKIE["count"])) {
    setcookie("count", $c);
}
else
{
    setcookie("count", $c, time() + 86400, '/');
}

Upvotes: 5

Views: 4717

Answers (3)

Ja͢ck
Ja͢ck

Reputation: 173582

The only way you can update a cookie's value without updating its expiry date is by adding the expiry date itself into the value; that's because a browser only sends you the names and values of the cookies.

if (isset($_COOKIE['count'])) {
    list($exp, $val) = explode('|', $_COOKIE['count'], 2);
    ++$val;
} else {
    $exp = time() + 86400;
    $val = 1;
}
setcookie('count', "$exp|$val", $exp, '/');

Upvotes: 3

Vyacheslav Voronchuk
Vyacheslav Voronchuk

Reputation: 2463

You can save expiry date in other cookie. When you update your cookie, just read expiry date from it and use it in your update.

Upvotes: 0

symcbean
symcbean

Reputation: 48357

You can't - PHP doen't know when the cookie will expire nor dose javascript (unless you copy the expiry time into the cookie contents).

Upvotes: 0

Related Questions