3

When I logout by destroying the session and start another one it always shows me the first session info I started $_SESSION['username'];

What I mean here is that : I started a session the first time I logged with this username --> AAAAAA And destroyed the session using the file logout.php which contains this code :

session_start();
session_destroy();
header("location: login.php");

and login with another username ---> BBBBBB and it always shows me the first username I logged in with---> AAAAAA

Where is the problem here

Here is the code (login.php)

<?php
        session_start();
        require_once "config/db.php";
        if(isset($_POST['login'])){     
        $username       = trim(mysql_real_escape_string($_POST['username']));
        $password       = trim(mysql_real_escape_string(md5($_POST['password']))); 
        $query          = mysql_query("SELECT * FROM `users` WHERE username='$username' AND password='$password' ")  or die(mysql_error());
         $rows           = mysql_num_rows($query);

        if($rows == 1){

            while($info = mysql_fetch_object($query)){            
                $dbusername = $info->username;
                $dbpassword = $info->password;
            }

            if($dbusername == $username && $dbpassword == $password){                   
                header("Location: index.php");         
                $_SESSION['username'] = $username;  
            }       

        }else{

        }
    }
?>

the index.php :

  <?php session_start();?>
  <h3><?php echo $_SESSION['username']; ?></h3>
4

3 回答 3

6

来自文档

为了完全终止会话,例如注销用户,还必须取消设置会话 ID。如果使用 cookie 传播会话 id(默认行为),则必须删除会话 cookie。setcookie() 可以用于此。

示例

session_unset();
session_destroy();
session_write_close();
setcookie(session_name(),'',0,'/');
session_regenerate_id(true);
于 2013-05-26T13:48:41.553 回答
1

我同意@Valery Viktorovsky,但是,由于您在销毁会话后PHP 7无法使用...session_regenerate_id(true);

这里的变更日志说:

7.0.0 - session_regenerate_id() saves old session data before closing.

这个适用于 PHP 7 或更高版本:

ob_start();
session_start();
session_unset();
session_regenerate_id(true);
session_unset();
session_destroy();
session_write_close();
setcookie(session_name(),'',0,'/');
header('LOCATION: index.php');

所以你可以试试这个,如果你不想

于 2017-04-02T11:42:01.343 回答
0

这是我的例子:

//Delete all previous PHPSESSID cookies
$past = 60 * 60 * 24 * 365 * 10;
setcookie('PHPSESSID', false, time() - $past);
//Delete all the data in the $_SESSION
$_SESSION = array();
//Delete the old session file (true) and create a new session id
session_regenerate_id(true);
于 2021-06-20T00:45:39.393 回答