尽管会话session_destroy()

时间:2019-09-30 08:31:25

标签: php session-variables

我正在开发具有会话的系统,在该系统中,我成功登录后将代码放入了启动会话的过程,并为诸如$_SESSION['email']之类的会话变量分配了值。另外,我放置了一个会话销毁代码,但该会话似乎并未销毁。我有以下文件- index.php 此文件使用以下代码授予用户访问正确凭据的权限:

if(password_verify($password,$dbpass)){
    $stmt = $conn->prepare("SELECT name, image FROM admins WHERE email=?");
    $stmt->bind_param("s",$email);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($name,$image);
    $stmt->fetch();
    $_SESSION['name'] = $name;
    $_SESSION['email'] = $email;
    $_SESSION['image'] = $image;
    header("Location:insert.php");
}

通过设置会话变量并将其重定向到预期的文件,它可以正常工作。在文件insert.php中,我导入了文件session.php,其代码如下:

session_start();
if(!isset($_SESSION['email'])){
    header("Location:index.php");
}

另外,我有一个logout.php文件,其中包含以下代码:

if(isset($_SESSION['email'])){
    session_destroy();
}
header("Location: index.php");

运行logout.php后,如果我再次尝试访问文件insert.php,尽管会话文件已导入其中,它也会打开。应该将其重定向到index.php文件。怎么了?任何人都可以帮忙。

2 个答案:

答案 0 :(得分:0)

您的会话和$ _SESSION服务器变量是分开的。 会话将中断,但变量不会为空。

尝试一下:

session_start();
session_destroy();

//Now you can choose whether you want to unset all sessions, or specific one(s):
$unset_sessions = ['email'];

foreach($_SESSION as $session => $session_value) {
   if (in_array($session, $unset_sessions))
      unset($_SESSION[$session]);
}

//Or all of them:
$_SESSION = [];

还可以从中创建一个函数,这很有趣:

function breakSessions($specifics= []) {

   if (!empty($specific)) { //Handle specifics
      foreach($_SESSION as $session => $session_value) {
         if (in_array($session, $specifics))
            unset($_SESSION[$session]);
      }
   } else {
      $_SESSION = [];
   }

}

breakSessions(['login', 'remember_me']) //Specifics;
breakSessions(); //All of them```

答案 1 :(得分:0)

if(isset($_SESSION['email'])){
    session_start();
    session_destroy();
}
header("Location: index.php");

在没有“开始”之前,您无法销毁会话。建议使用一个包含“ session_start();”的会话文件。从中构建模板,以便每个页面始终具有“ session_start();”