2024-02-28 09:00:02

移除一块饼干

当我想要删除Cookie时,我会尝试

unset($_COOKIE['hello']);

我在firefox的cookie浏览器中看到cookie仍然存在。我怎么才能真正去掉饼干呢?


当前回答

我发现在Chrome浏览器中,除非你在cookie中定义最后三个参数,否则不可能取消设置cookie。域名,它是安全的,只有http…

if (isset($_COOKIE['user_id'])) {
unset($_COOKIE['user_id']); 
setcookie("user_id", "", time() - 3600, "/", 'yourdomain.com',true,true);
header('Location: /');
} else {
/* other code here */
}

我就是这样让它为我工作的。 阅读文档:官方PHP站点中关于cookie的所有内容

其他回答

$cookie_name = "my cookie";
$cookie_value = "my value";
$cookie_new_value = "my new value";

// Create a cookie,
setcookie($cookie_name, $cookie_value , time() + (86400 * 30), "/"); //86400 = 24 hours in seconds

// Get value in a cookie,
$cookie_value = $_COOKIE[$cookie_name];

// Update a cookie,
setcookie($cookie_name, $cookie_new_value , time() + (86400 * 30), "/");

// Delete a cookie,
setcookie($cookie_name, '' , time() - 3600, "/"); //  time() - 3600 means, set the cookie expiration date to the past hour.

一个干净的删除cookie的方法是清除$_COOKIE值和浏览器cookie文件:

if (isset($_COOKIE['key'])) {
    unset($_COOKIE['key']);
    setcookie('key', '', time() - 3600, '/'); // empty value and old timestamp
}

你必须删除cookie与php在你的服务器,也与js为您的浏览器..(他们是用php做的,但cookie文件也在浏览器客户端中):

一个例子:

if ($_GET['action'] == 'exit'){
            // delete cookies with js and then in server with php:
            echo '
            <script type="text/javascript">
                var delete_cookie = function(name) {
                     document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:01 GMT;";
                };
                delete_cookie("madw");
                delete_cookie("usdw");
            </script>
            ';
unset($_COOKIE['cookie_name']);
unset($_COOKIE['cookie_time']);

您可以根据cookie值设置会话变量

session_start();

if(isset($_COOKIE['loggedin']) && ($_COOKIE['loggedin'] == "true") ){
$_SESSION['loggedin'] = "true";
}

echo ($_SESSION['loggedin'] == "true" ? "You are logged in" : "Please Login to continue");

你可以简单地使用这个自定义函数:

function unset_cookie($cookie_name) {
    if (isset($_COOKIE[$cookie_name])) {
        unset($_COOKIE[$cookie_name]);
        setcookie($cookie_name, null, -1);
    } else { return false; }
}

如果您想删除$_COOKIE['user_account']。 只使用:

unset_cookie('user_account');