Home >Backend Development >PHP Tutorial >Why Doesn't `unset($_COOKIE['cookie_name'])` Remove a Cookie, and How Can I Do It Properly?

Why Doesn't `unset($_COOKIE['cookie_name'])` Remove a Cookie, and How Can I Do It Properly?

DDD
DDDOriginal
2024-12-14 14:08:13143browse

Why Doesn't `unset($_COOKIE['cookie_name'])` Remove a Cookie, and How Can I Do It Properly?

How to effectively remove a cookie

When attempting to remove a cookie using unset($_COOKIE['hello']);, you may notice that the cookie remains visible in your browser's cookie manager. This is because the unset function only removes the cookie from PHP's internal memory, not from the browser.

To permanently remove a cookie, the following steps are necessary:

  1. Unset the cookie from PHP's internal memory:

    unset($_COOKIE['remember_user']);
  2. Set the cookie to expire in the past (e.g., 1 hour ago):

    setcookie('remember_user', '', time() - 3600, '/');
  3. Ensure that the cookie path matches the original cookie:
    The setcookie function takes a path as its third parameter. This path should match the path specified when the cookie was originally created. If the paths do not match, PHP may not remove the cookie properly.
  4. Return a success message (optional):

    return true;

By following these steps, you can effectively remove a cookie from the browser and prevent it from being used in future requests.

The above is the detailed content of Why Doesn't `unset($_COOKIE['cookie_name'])` Remove a Cookie, and How Can I Do It Properly?. 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