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

Shi*_*pak 31 php session

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

脚本1

<?php
session_start();
session_destroy();
header("location:index.php");
?>
Run Code Online (Sandbox Code Playgroud)

脚本2

<?php
session_start();
session_unset();
session_destroy();
header("location:index.php");
?>
Run Code Online (Sandbox Code Playgroud)

脚本3

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

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

Frx*_*rem 61

PHP手册中session_destroy()页面:

<?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();
?>
Run Code Online (Sandbox Code Playgroud)

  • @MohammedNoureldin $params 正在获取当前参数,以确保使用相同的参数来删除它。它有助于此代码在使用非默认参数的情况下更普遍地工作。 (2认同)

irc*_*ell 11

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

session_start();
setcookie(session_name(), '', 100);
session_unset();
session_destroy();
$_SESSION = array();
Run Code Online (Sandbox Code Playgroud)

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

  • @ Frxstrem的解决方案更完整(因为它考虑了使用的确切cookie参数).用那个代替...... (3认同)

Hai*_*vgi 6

Session_unset();只会破坏会话变量。要结束会话session_destroy();,还调用了另一个函数,该函数也会破坏会话。

更新 :

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

  • `session_destroy()` 不接触 cookie。来自文档:`为了完全终止会话,比如注销用户,会话 ID 也必须取消设置。如果使用 cookie 来传播会话 ID(默认行为),则必须删除会话 cookie。setcookie() 可以用于那个。` http://us3.php.net/manual/en/function.session-destroy.php (3认同)

Opt*_*ime 6

<?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;
?>
Run Code Online (Sandbox Code Playgroud)

  • 虽然此代码片段可以解决问题,但[包括解释](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)确实有助于提高帖子的质量。请记住,您是在为将来的读者回答问题,而那些人可能不知道您建议代码的原因。 (5认同)