从PHP中的会话注销的正确方法

时间:2010-08-18 13:22:17

标签: php session

我已经阅读了很多关于注销脚本的php教程,我想知道从会话注销的正确方法是什么!

脚本1

<?php
session_start();
session_destroy();
header("location:index.php");
?>

脚本2

<?php
session_start();
session_unset();
session_destroy();
header("location:index.php");
?>

脚本3

<?php
session_start();
if (isset($_SESSION['username']))
{
    unset($_SESSION['username']);
}
header("location:index.php");
?>

还有更有效的方法吗?可以通过重新登录来创建会话,所以我是否应该使用session_destroy()并使用unset($ _ SESSION ['variable'])来代替?上面哪3个脚本更优选?

4 个答案:

答案 0 :(得分:59)

session_destroy()中的PHP manual页面:

<?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();
?>

答案 1 :(得分:11)

就个人而言,我会做以下事情:

session_start();
setcookie(session_name(), '', 100);
session_unset();
session_destroy();
$_SESSION = array();

这样,它会杀死cookie,破坏内部存储的所有数据,并销毁会话信息的当前实例(session_destroy忽略该实例)。

答案 2 :(得分:4)

Session_unset();只会破坏会话变量。要结束会话,还有另一个名为session_destroy();的函数,它也会破坏会话。

更新:

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

答案 3 :(得分:2)

<?php
// Initialize the session.
session_start();
// Unset all of the session variables.
unset($_SESSION['username']);
// Finally, destroy the session.    
session_destroy();

// Include URL for Login page to login again.
header("Location: login.php");
exit;
?>