Teimuraz
Teimuraz

Reputation: 9335

php: how to correctly remove all cookies?

Ideally, to delete cookie in php, one should set exactly the same parameters when the cookie was created, except value and expire time:

Creating cookie:

setcookie('cookie1', 'value1', time()+10000, '/', 'domain.com', false, true);

Delete cookie:

setcookie('cookie1', '', time()-10000, '/', 'domain.com', false, true);

But, how can I get parameters that was set creating cookie when I want to delete it? assuming that I'm not tracking these params, for example, cookies was created with some third party libraries

Yes, there is method to delete:

setcookie($name, '', time() - 1000, "/");
setcookie($name, '', time() - 1000);

But is it "ideally" correct approach? do all browsers (including old) support this?

Any way, what is the method to correctly delete all cookies for sure for all browsers

How can I set exactly the same params deleting cookies (If I don't track cookies creation)?

Upvotes: 3

Views: 6381

Answers (1)

user6763587
user6763587

Reputation:

if (isset($_SERVER['HTTP_COOKIE'])) {//do we have any
    $cookies = explode(';', $_SERVER['HTTP_COOKIE']);//get all cookies 
    foreach($cookies as $cookie) {//loop
        $parts = explode('=', $cookie);//get the bits we need
        $name = trim($parts[0]);
        setcookie($name, '', time()-1000);//kill it
        setcookie($name, '', time()-1000, '/');//kill it more
    }
}

from the notes: http://php.net/manual/en/function.setcookie.php

Upvotes: 2

Related Questions