Home  >  Article  >  Backend Development  >  How to Delete All Cookies Associated with a Specific Domain in PHP?

How to Delete All Cookies Associated with a Specific Domain in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-25 05:57:56686browse

How to Delete All Cookies Associated with a Specific Domain in PHP?

How Can I Remove All Cookies of a Specific Domain with PHP?

When a user logs out of a website, it's often desirable to delete all the cookies associated with that website. Unfortunately, using the setcookie() function to set a cookie to false isn't effective for this purpose.

Solution: Using PHP setcookie()

To remove all cookies associated with a specific domain, use the following PHP code:

<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 retrieves the HTTP cookies for the current request, splits them into individual key-value pairs, and for each key, it sets the value to an empty string and expires the cookie using time()-1000. Additionally, it sets the cookie path to "/", ensuring it affects all paths on the domain.

The above is the detailed content of How to Delete All Cookies Associated with a Specific Domain 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