【问题标题】:proper way to logout from a session in PHP从 PHP 中注销会话的正确方法
【发布时间】:2011-03-31 13:29:54
【问题描述】:

我已经阅读了许多关于注销脚本的 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 个脚本中哪一个更可取?

【问题讨论】:

  • 请记住,您希望在标头重定向后 exit() 以避免暴露可能跟随的内容...

标签: php session


【解决方案1】:
<?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;
?>

【讨论】:

  • 虽然这段代码 sn-p 可以解决问题,但including an explanation 确实有助于提高帖子的质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
  • 刚刚没有谢谢@DerekBrown
【解决方案2】:

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

更新:

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

【讨论】:

  • session_destroy() 不接触 cookie。来自文档:In order to kill the session altogether, like to log the user out, the session id must also be unset. If a cookie is used to propagate the session id (default behavior), then the session cookie must be deleted. setcookie() may be used for that.us3.php.net/manual/en/function.session-destroy.php
【解决方案3】:

来自PHP manual中的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();
?>

【讨论】:

  • 谢谢!这非常有用。
  • 能解释一下这部分吗? $["path"], $params["domain"], $params["secure"], $params["httponly"]);。我没明白你在这里做什么
  • @MohammedNoureldin $params 正在获取当前参数,以确保使用相同的参数来删除它。在使用非默认参数的情况下,它可以帮助此代码更普遍地工作。
【解决方案4】:

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

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

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

【讨论】:

  • 是否设置cookie(session_name(), '', 100); @ircmaxell 发布的代码会比@Frxstrem 发布的代码有更好的行为?
  • @Frxstrem 的解决方案更完整(因为它考虑了所使用的确切 cookie 参数)。改用那个...
猜你喜欢
  • 1970-01-01
  • 2017-01-26
  • 2012-01-21
  • 2015-08-01
  • 2015-03-03
  • 2010-11-16
  • 2016-11-13
  • 2016-01-02
  • 1970-01-01
相关资源
最近更新 更多