5

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, '/');
}
Paul R
  • 208,748
  • 37
  • 389
  • 560
UZSTYLE GROUP
  • 65
  • 2
  • 6
  • 1
    not possible, since there is no such thing as "updating" a cookie, its also not possible to receive the remaining ttl. What you could do tough sereialize your data & ttl and save them as value, then you can read them and set the new ttl & data accordingly – Hannes Nov 16 '12 at 15:00

3 Answers3

3

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, '/');
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
  • @UZSTYLEGROUP You'd have to clear any existent cookies first, because the format would have changed. – Ja͢ck Nov 16 '12 at 15:27
  • Cookie value: 1353168251%7C1 What is it ? – UZSTYLE GROUP Nov 16 '12 at 16:02
  • @UZSTYLEGROUP It contains the timestamp (left of `%7C`) and the actual value on the right, i.e. `1`, – Ja͢ck Nov 16 '12 at 16:03
  • how to make limit. `if(20 > $_COOKIE["count"]){ if (isset($_COOKIE['count'])) { list($exp, $val) = explode('|', $_COOKIE['count'], 2); ++$val; } else { $exp = time() + 86400; $val = 1; } setcookie('count', "$exp|$val", $exp, '/'); readfile(file.mp3) }` – UZSTYLE GROUP Nov 16 '12 at 16:09
  • `$c` or `$val` are just variable names; rename where appropriate. – Ja͢ck Nov 16 '12 at 16:15
0

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).

symcbean
  • 47,736
  • 6
  • 59
  • 94
0

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.

Vyacheslav Voronchuk
  • 2,403
  • 19
  • 16