如何在 PHP 中取消设置 cookie?

问题描述:

我需要弄清楚如何取消设置此 cookie.到目前为止我尝试过的一切都失败了.

I need to figure out how to unset this cookie. Everything I tried so far has failed.

这是我目前取消设置的方式,但似乎不起作用.

This is how I am currently unsetting it and it doesn't seem to work.

setcookie("user_id", $user_id, time() - 7200);

我是这样设置的:

setcookie("user_id", $user_id, time() + 7200);

我有一个名为 set_session_from_cookie() 的函数,用于检查是否设置了 cookie,如果设置了,它会使用 cookie 启动一个新会话.

I have this function called set_session_from_cookie() that checks if a cookie is set, and if it is set, it starts a new session using the cookie.

问题是当我在我的页面上使用它时,我无法注销.我认为这是因为我无法取消设置会话.

The problem is that when I use this on my page I am unable to logout. I assume this is because I am unable to unset the session.

我有这个功能的原因是如果用户在结束会话后想要被记住,他们可以通过调用cookie来重新启动会话.

The reason I have this function is if a user wants to be remembered after they end the session, they can restart the session by calling the cookie.

function set_session_from_cookie()
{
    if (isset($_SESSION['user_id'])) {
        echo '';
    } else {
        $_SESSION['user_id']=$_COOKIE['user_id'];
    }
}

退出:

<?php
require'core.php';
session_destroy();

setcookie("user_id", "", time() - 7200);
header('Location:/social_learning/site_pages/starter-template.php');

我使用以下代码设置我的 cookie:

I set my cookie with the following code:

if ($rememberme == "on") {
    $user_id = mysql_result($query_run, 0, 'id');
    setcookie("user_id", $user_id, time() + 7200);
    $_SESSION['user_id'] = $user_id;
    redirect('home_page.php');
} else {
    if ($rememberme == "") {
        echo 'ok';
        $user_id = mysql_result($query_run, 0, 'id');
        echo $user_id;
        $_SESSION['user_id'] = $user_id;
        redirect('home_page.php');
    }
}

如何在不使用我创建的函数的情况下使用保存的 cookie 重新启动会话?由于该功能似乎导致用户无法再注销.

How can I restart the session using the saved cookie without using the function I created? Since the function seems to be causing the user to no longer be able to logout.

这个问题的解决方案是我需要设置正确的路径来取消设置 cookie,因为我是从我最初设置的不同文件中取消设置的

The solution to this problem was that the I needed to set the correct path to unset the cookie since I was unsetting it from a different file that I originally set it in.

我通过在浏览器 cookie 中查找 cookie 来确定我需要使用哪个路径来取消设置,一旦我在浏览器中找到 cookie,该路径就会列在 cookie 附近.所以我然后像这样设置 cookie 的路径:

I found out which path I needed to use for the unset by looking for the cookie inside my browser cookies, and once I found the cookie inside my browser, the path was listed near the cookie. So I then set the path to the cookie like so:

setcookie("user_id", $user_id, time() - 1, "/social_learning/site_pages");

最后一个参数是路径.它奏效了.

The last parameter is the path. And it worked.

我原来的 setcookie 看起来像这样:

My original setcookie looks like this:

setcookie("user_id", $user_id, time() + 7200, "");