Remove a cookie

2018-12-31 16:49发布

When I want to remove a Cookie I try

unset($_COOKIE['hello']);

I see in my cookie browser from firefox that the cookie still exists. How can I really remove the cookie?

标签: php cookies
21条回答
长期被迫恋爱
2楼-- · 2018-12-31 16:54

When you enter 0 for time, you mean "now" for the browser.

setcookie("key", NULL, 0, "/");

I checked it in chrome browser that gives me:

Name: key
Content: Deleted
Created: Sunday, November 18, 2018 at 2:33:14 PM
Expires: Sunday, November 18, 2018 at 2:33:14 PM
查看更多
看淡一切
3楼-- · 2018-12-31 16:59

A clean way to delete a cookie is to clear both of $_COOKIE value and browser cookie file :

if (isset($_COOKIE['key'])) {
    unset($_COOKIE['key']);
    setcookie('key', '', time() - 3600, '/'); // empty value and old timestamp
}
查看更多
初与友歌
4楼-- · 2018-12-31 17:00

Just set the expiration date to one hour ago, if you want to "remove" the cookie, like this:

setcookie ("TestCookie", "", time() - 3600);

or

setcookie ("TestCookie", "", time() - 3600, "/~rasmus/", "example.com", 1);

Source: http://www.php.net/manual/en/function.setcookie.php

You should use the filter_input() function for all globals which a visitor can enter/manipulate, like this:

$visitors_ip = filter_input(INPUT_COOKIE, 'id');

You can read more about it here: http://www.php.net/manual/en/function.filter-input.php and here: http://www.w3schools.com/php/func_filter_input.asp

查看更多
余生无你
5楼-- · 2018-12-31 17:00

Most of you are forgetting that this will only work on a local machine. On a domain you will need a pattern like this example.

setcookie("example_cookie", 'password', time()-3600, "/", $_SERVER['SERVER_NAME']);
查看更多
浅入江南
6楼-- · 2018-12-31 17:02

It's simple!

setcookie("cookiename", "cookievalue", 1);
查看更多
明月照影归
7楼-- · 2018-12-31 17:03

To delete cookie you just need to set the value to NULL:

"If you've set a cookie with nondefault values for an expiration time, path, or domain, you must provide those same values again when you delete the cookie for the cookie to be deleted properly." Quote from "Learning PHP5" book.

So this code should work(works for me):

Setting the cookie: setcookie('foo', 'bar', time() + 60 * 5);

Deleting the cookie: setcookie('foo', '', time() + 60 * 5);

But i noticed that everybody is setting the expiry date to past, is that necessary, and why?

查看更多
登录 后发表回答