用户注销时删除PHP cookie

时间:2012-12-13 15:17:01

标签: php session cookies

我开始创建一个登录系统,该系统使用cookie来“记住我”功能。一切正常,但我在用户退出时删除cookie时遇到问题。

如果用户没有选中“记住我”框并成功登录I.e.如果没有创建cookie,则注销功能会按预期工作并加载登录框。

如果他们不执行后者并且用户点击退出按钮,则cookie仍然存在并显示他们仍然登录。

如果有人可以清楚地说明饼干为什么不会删除,我将非常感激。

以下是我正在使用的代码:

用户尝试登录后运行的PHP代码:

// If the form has been submitted
if(isset($_POST['login'])):

    // Protect from unwanted code/string context
    $username = strip_tags(addslashes(trim($_POST['username'])));
    $string = strip_tags(addslashes(trim($_POST['password'])));
    $remember = strip_tags(addslashes(trim($_POST['remember'])));

    // Pass the returned variables from functions to a local versions
    $password = salting($string);   // Salt Password Preperation
    $link = db_connect();           // DB connection

    // Connect to the database and try to find a login match
    $result = mysqli_query($link,"SELECT * FROM web_users WHERE username='".$username."' AND password='".$password."'");
    $row    = mysqli_fetch_object($result);

    // Create erronous results if submitted data is invalid
    if (mysqli_num_rows($result) !== 1):
        $errmsg[0] = "Invalid Username or Password, please re-try";
    endif;

    $e_login = serialize($errmsg);

    // If validation passes then continue
    if (!$errmsg):
        // Increment the login_count field by 1
        $row->login_count++;
        $count = $row->login_count;

        // Retrieve the date for admin purposes
        $date = date('Y-m-d-h:i:s'); // Y=year (4 digits) m=month (leading zero) h=hour i=minutes s=seconds

        // Salt Password Preperation
        $string = session_id();
        $login_id = salting($string);

        // Connect to the database and update the related row
        $update = mysqli_query($link,"UPDATE web_users
                                      SET login_count='".$count."',
                                          login_last='".$date."',
                                          login_id='".$login_id."',
                                          logged='1'
                                      WHERE id='".$row->id."'")

                                      or die(mysqli_error($link));

        // Create a multi-dimensional session array
        $_SESSION['login'] = array('user'       => $row->display_name,
                                   'id'         => $row->id,
                                   'user_level' => $row->user_level);

        if($remember == 1):
            setcookie("login_user",session_id(),time() + (86400*7)); // 604800 = 1 week
        endif;

        // Free the memory and close the connection
        mysqli_free_result($result);
        mysqli_close($link);

        // Take the user to the successive page if no errors
        header("location: /");
    endif;
endif;

用于创建注销元素的HTML代码:

<a href="/logout" title="Logout">
    <img src="<? echo ASSETS . IMAGES . ICONS . GENERAL; ?>logout.png" alt="User Logout">
</a>

用户注销时运行的PHP代码:

function logout() {
    // Load the db connect function to pass the link var
    $link = db_connect();

    if(is_array($_SESSION['login'])):
        // Update the logged field to show user as logged out
        $update = mysqli_query($link,"UPDATE web_users SET logged='0' WHERE id='".$_SESSION['login']['id']."'") or die(mysqli_error($link));

        // Free the memory and close the connection
        mysqli_free_result($update);
        mysqli_close($link);

        // Unset all of the session variables.
        $_SESSION = array();

        // If it's desired to kill the session, also delete the session cookie.
        // Note: This will destroy the session, and not just the session data!
        if(isset($_COOKIE[session_name()])):
            setcookie(session_name(), '', time()-7000000, '/');
        endif;

        // Finally, destroy the session.
        session_destroy();

        // Take the user to the successive page if no errors
        header("location: /");
    endif;
}

3 个答案:

答案 0 :(得分:6)

用户在使用“记住我”复选框登录您的网站后,将拥有两个 Cookie。会话Cookie默认为PHPSESSID,并且记住我的Cookie login_user。要删除会话,只需使用以下代码删除sesion cookie:

    if(isset($_COOKIE[session_name()])):
        setcookie(session_name(), '', time()-7000000, '/');
    endif;

问题在于,除此之外,您需要使用以下代码取消设置记住我的cookie。

    if(isset($_COOKIE['login_user'])):
        setcookie('login_user', '', time()-7000000, '/');
    endif;

答案 1 :(得分:1)

要删除Cookie,您应该设置过去的过期日期:

setcookie('login_user', '',time() - 3600);

您有此规则,但显式添加路径参数,虽然您在设置Cookie时未使用该路径,但这可能是问题所在。

答案 2 :(得分:1)

我会猜测你的代码

 if(isset($_COOKIE[session_name()])):
      setcookie(session_name(),'',time()-7000000,'/');
 endif;

是你的问题。很可能isset返回false。如果可能的话,我会将其从if语句中删除。

此外,如下文评论中所述。你使用session_start()了吗?上面的代码中没有对它的引用。这会导致session_name()返回空。