开发者

session_destroy() and setcookie fail

开发者 https://www.devze.com 2023-01-24 07:27 出处:网络
I\'m trying to logout of my page but session_destroy and setting cookies does not work. Here\'s my code:

I'm trying to logout of my page but session_destroy and setting cookies does not work. Here's my code:

    $page = $_GET["page"];
    if ($page == "logout") {
if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
    );
}

session_destroy();


echo <<<html
        <br /><br /><br /><p align="center"><b><font color="#000080">You've successfully logged out.</font></b></p>
        <p align="right"><b><font size="3" color="#FF0000">Redirecting...</font></b></td>
html;
echo ("<META HTTP-EQUIV=Refresh CONTENT=\"4; URL=index.php\">");
exit ();

But its not working - the session is not destroyed and cookies remain the same. I've also tried just setting a cookie to a different value with no success. Other parts of the code create cookies, access and use them, but in the logout part I cant destroy them. Can someone tell me what's wrong here? Should cookies and sessions be set/unset/destroyed at the beginning of the page like 开发者_如何学编程session_start? Or is something else wrong?


setcookie() must be called before your scripts generates any output, as is affects the headers which are sent to the client before the actual response.

The code snippet you posted looks like you echo some stuff before the posted code is called (the output string does not contain an opening html tag). So make sure that your code is placed before any output is echoed, but after session_start() is called, then it should work.


You have to call session_start() before session_destroy() will work as session_destroy operates on the current session, which does not exist if you have not called session start.


Does the page have a session_start() before session_destroy()? It needs to be.


if we don't call

session_start()

at the beginning of the page, we cannot have session variables to operate on that page.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号