0

No clue why this is doing this. But my logout.php code works fine and redirects to the home page and the session is destroyed. When I go back to a certain page it brings up an old session I don't get it.

Heres my login file

   $_SESSION['id'] = $row['user_id'];
   $_SESSION['username'] = $row['username'];
   setcookie('id', $row['user_id'], time() + (60 * 60 * 24 * 2));
   setcookie('username', $row['username'], time() +(60 * 60 * 24 * 2));

Here is my logout file

   // if the user is logged in, delete the cookie to log them out
   session_start();
   if (isset($_SESSION['id'])) {
     $_SESSION = array();

     // delete the user id and the username cookie by setting their expirations to an hour ago (3600)
   if (isset($_COOKIE[session_name()])) {  
      setcookie('session_name()', '', time() - 3600);

   }
   //destroy the session
session_unset();
    session_destroy();
  }

   //delete the user id and username cookies
   setcookie('id', '', time() - 3600);
   setcookie('username', '', time() - 3600);
 unset($_COOKIE['id']);
 unset($_COOKIE['username']);
     unset($_SESSION['id']);
     unset($_SESSION['username']);
   // redirect to the home page
   $home_url = 'http://page.com/';
   header('Location: ' . $home_url);
   exit();

Here is the code I have on my page:

session_start();

// If the session vars aren't set, try to set them with a cookie
if (!isset($_SESSION['id'])) {
  if (isset($_COOKIE['id']) && isset($_COOKIE['username'])) {
    $_SESSION['id'] = $_COOKIE['id'];
    $_SESSION['username'] = $_COOKIE['username'];
  }
} 

This code works fine on the home page, but when I got into a sub directory it brings up a random old session.

4

1 回答 1

1

您是否尝试过在销毁会话之前先取消设置会话,而不是仅仅销毁会话?

unset($_SESSION['id']);
unset($_SESSION['username']);

然后调用你的 session_destroy() 函数。

另外,我在某处读到(不记得在哪里,不幸的是 - 可能是这样,甚至......)将直接 SQL 结果($row['id'])存储在 cookie 中不是一个好主意。最好先将结果存储在 $_SESSION 中,然后将 $_SESSION 存储在 cookie 中。

于 2013-03-21T02:53:56.800 回答