Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
721 views
in Technique[技术] by (71.8m points)

session - how to unset cookie in PHP?

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);

This is how I set it:

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

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.

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'];
    }
}

Logout:

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

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

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');
    }
}

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Set the cookie's expiration date to a time in the past (like one second after epoch, for example).

setcookie("yourCookie", "yourValue", 1);

This will cause the cookie to expire.

1 is used instead of 0, because 0 sets the cookie to expire at the end of the session.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...