注销功能不起作用(会话未被杀死)

时间:2012-06-14 22:14:31

标签: php

function killsession()
{
  //  global $_SESSION;
    $_SESSION = array();
    if (session_id() != "" || isset($_COOKIE[session_name()])) {
        setcookie(session_name(), '', time() - 42000, '/');
    }
    session_unset();
    session_destroy();
    header("Location: "index");

}

在运行此功能后,为什么$ _SESSION ['userid']仍然存在的任何想法?我确实保持登录状态。

会话名称和start()设置在每个页面的顶部。

2 个答案:

答案 0 :(得分:2)

PHP session_destroy()手册中所示:

  

session_destroy()销毁与当前会话相关的所有数据。它不会取消设置与会话关联的任何全局变量,也不会取消设置会话cookie。要再次使用会话变量,必须调用session_start()

     

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

直接来自PHP手册的示例:

<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();

// Unset all of the session variables.
$_SESSION = array();

// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
    );
}

// Finally, destroy the session.
session_destroy();
?>

将此示例应用于您的函数:

function killsession()
{
  // start the session, if started before, comment
  session_start();

  // Unset all of the session variables. 
  $_SESSION = array();

  // destroy the session, and not just the session data!
  if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
    );
  }

  // destroy the session.
  session_destroy();

  // direct user
  header("Location: index.php");
}

考虑这两个会话变量:

$_SESSION['userid']=25;
$_SESSION['userName']='Super BuBu';

print_r($_SESSION);的输出将为:

Array ( [userid] => 25 [userName] => Super BuBu )

调用killsession()函数后,输出将为:

Array ( );

working example。由于先前的输出和标题由print_rsession交互执行,因此假设错误出现在此环境中。

答案 1 :(得分:0)

尝试

 function killsession() {
     unset($_SESSION['userid']);
     session_destroy();
     header("Location: "index");

 }