how to delete all cookies of my website in php

Viewed 163743

I'm wondering if I can delete all my website's cookies when a user click on logout, because I used this as function to delete cookies but it isn't work properly:

setcookie("user",false);

Is there a way to delete one domain's cookies in PHP?

12 Answers

PHP setcookie()

Taken from that page, this will unset all of the cookies for your domain:

// unset cookies
if (isset($_SERVER['HTTP_COOKIE'])) {
    $cookies = explode(';', $_SERVER['HTTP_COOKIE']);
    foreach($cookies as $cookie) {
        $parts = explode('=', $cookie);
        $name = trim($parts[0]);
        setcookie($name, '', time()-1000);
        setcookie($name, '', time()-1000, '/');
    }
}

http://www.php.net/manual/en/function.setcookie.php#73484

$past = time() - 3600;
foreach ( $_COOKIE as $key => $value )
{
    setcookie( $key, $value, $past, '/' );
}

Even better is however to remember (or store it somewhere) which cookies are set with your application on a domain and delete all those directly.
That way you can be sure to delete all values correctly.

make sure you call your setcookie function before any output happens on your site.

also, if your users are logging out, you should also delete/invalidate their session variables.

Use the function to clear cookies:

function clearCookies($clearSession = false)
{
    $past = time() - 3600;
    if ($clearSession === false)
        $sessionId = session_id();
    foreach ($_COOKIE as $key => $value)
    {
        if ($clearSession !== false || $value !== $sessionId)
            setcookie($key, $value, $past, '/');
    }
}

If you pass true then it clears session data, otherwise session data is preserved.

I had to add the following to the top answer to actually remove a few cookies that wouldn't go away:

foreach($_COOKIE as $cook) {
    setcookie($cook, '', time()-1000);
    setcookie($cook, '', time()-1000, '/');
}
Related