【问题标题】:Logout PHP Script注销 PHP 脚本
【发布时间】:2014-02-14 17:31:20
【问题描述】:

这是我的脚本:

<?php
  // If the user is logged in, delete the session vars to log them out
  session_start();
  if (isset($_SESSION['user_id'])) {
    // Delete the session vars by clearing the $_SESSION array
    $_SESSION = array();

    // Delete the session cookie by setting its expiration to an hour ago (3600)
    if (isset($_COOKIE[session_name()])) {      setcookie(session_name(), '', time() - 3600);    }

    // Destroy the session
    session_destroy();
  }

  // Delete the user ID and username cookies by setting their expirations to an hour ago (3600)
  setcookie('user_id', '', time() - 3600);
  setcookie('username', '', time() - 3600);

  // Redirect to the home page
  $home_url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/index.php';
  header('Location: ' . $home_url);
?>

登录网站后无法退出。我真的需要 cookie 登录吗?或者我可以把它拿出来吗?

【问题讨论】:

  • 如果您没有在客户端访问 javascript 中的 cookie,您可以只使用 PHP 会话并避免使用 cookie。
  • 我之前没有使用过cookie登录。我只是在每个页面上启动会话,并在注销时销毁会话。但这只是我。
  • 我更喜欢 WreithKassan 这个想法

标签: php logout


【解决方案1】:

尝试更简单的方法,销毁所有会话 cookie

session_start();
session_destroy();
$home_url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/index.php';
header('Location: ' . $home_url);

【讨论】:

    【解决方案2】:

    我推荐使用这种方法,

    <?php
    //User session in ['user']
    if($_SESSION['user_id']){
      session_start();
      session_unset();
      session_destroy();
      session_write_close();
      setcookie(session_name(),'',0,'/');
      session_regenerate_id(true);
    }
    ?>
    

    我建议您使用该方法 , 为什么?因为该方法在 PHP 中使用true destroy,delete cookie in browsernew set ID of session 的会话

    【讨论】:

      【解决方案3】:

      "为了完全终止会话,就像注销用户一样,还必须取消设置会话 ID。如果使用 cookie 传播会话 ID(默认行为),则必须删除会话 cookie。 setcookie() 可用于此。” 见:http://us1.php.net/session_destroy 和:http://us1.php.net/manual/en/function.session-id.php “警告 不要使用 unset($_SESSION) 取消设置整个 $_SESSION,因为这将禁用通过 $_SESSION 超全局变量注册会话变量。” 见:http://us2.php.net/manual/en/function.session-unset.php

      【讨论】:

        猜你喜欢
        • 2017-05-22
        • 2013-05-11
        • 2011-08-29
        • 1970-01-01
        • 1970-01-01
        • 2013-12-28
        • 1970-01-01
        • 2011-04-14
        • 2015-03-17
        相关资源
        最近更新 更多