Search code examples
phpcookiessetcookie

PHP rewrite cookie value without lifetime reset


I'm setting the cookie with life time till midnight comes.

setcookie('foo', 'bar', strtotime('today 23:59') );

How can I rewrite value of ['foo'] without resetting lifetime? For example setcookie('foo', 'foo-bar', /* current lifetime*/ );

How to get current lifetime of cookie with 'foo' key?


Solution

  • My way: save json encoded array such as

    $time_to_set = strtotime('today 23:59');
    $cookie = json_encode(array( 'foo' => 'bar', 'ttl' => $time_to_set, ));
    setcookie('foo', $cookie, $time_to_set );
    

    and to read cookie TTL:

    $cooke_personal_ttl = json_decode($_COOKIE['foo'], true)['ttl'];
    

    Or something like this..