Home >Backend Development >PHP Tutorial >How to Completely Delete a Cookie in PHP?

How to Completely Delete a Cookie in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-06 15:55:15279browse

How to Completely Delete a Cookie in PHP?

How to Effectively Remove a Cookie in PHP

In PHP, removing a cookie solely through the unset() function may not always be effective in completely removing it. To ensure a proper removal, it is recommended to combine the unset() function with an additional setcookie() call to overwrite the cookie with an expiration timestamp in the past.

To illustrate:

if (isset($_COOKIE['remember_user'])) {
    unset($_COOKIE['remember_user']); // Remove the cookie from the $_COOKIE array
    setcookie('remember_user', '', -1, '/'); // Set the cookie with an expiration timestamp in the past
    return true;
} else {
    return false;
}

In this example:

  • The unset($_COOKIE['remember_user']) line removes the cookie from the $_COOKIE array, which is a global array that holds all cookies sent by the client.
  • The setcookie('remember_user', '', -1, '/') line overwrites the cookie with an expiration timestamp of -1 (Unix timestamp in the past) and a path of '/'. This effectively removes the cookie from the client's browser.

Note that the setcookie() function takes four arguments:

  • The name of the cookie to remove
  • The value of the cookie to be removed (an empty string in this case)
  • An expiration timestamp in the past (-1)
  • The path in which the cookie was set (typically '/')

By following this method, you can reliably remove a cookie from both the PHP environment and the client's browser.

The above is the detailed content of How to Completely Delete a Cookie 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