Home >Backend Development >PHP Tutorial >Why Doesn\'t `setcookie(\'user\', false);` Delete All Website Cookies in PHP?

Why Doesn\'t `setcookie(\'user\', false);` Delete All Website Cookies in PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-10-24 18:37:44391browse

Why Doesn't `setcookie(

How to Delete All Website Cookies in PHP

You've encountered an issue where the setcookie("user", false); function is not effectively deleting all website cookies. This article explores the solution to this problem, providing a PHP snippet that addresses this specific requirement.

Solution: PHP's setcookie() Function

To unset all cookies for your domain using PHP, refer to the PHP documentation on setcookie(). The following code effectively achieves this:

<code class="php">// 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, '/');
    }
}</code>

This code iterates through all available cookies, deleting each one by setting the expiration to a past date and explicitly setting the cookie path to '/'.

For further reference, please consult the PHP documentation on setcookie() at http://www.php.net/manual/en/function.setcookie.php#73484.

The above is the detailed content of Why Doesn\'t `setcookie(\'user\', false);` Delete All Website Cookies in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn