注销问题/会话未被销毁

时间:2010-06-15 08:35:28

标签: php session

我在尝试登录时遇到问题..下面是我的登录代码

<?php 
session_start();
include("functions.php");
    connecttodb();

if(!empty($_SESSION['loggedin']) && !empty($_SESSION['username']))
{
    echo "already logged in";
header("refresh:3; url=main.php");

}

if(!empty($_POST['username']) && !empty($_POST['password']))
{
     $username = $_POST['username'];
    $password = $_POST['password'];


     $sql="SELECT * FROM admin WHERE admin_username ='".$username."' AND admin_password= '".$password."'";
     $result=mysql_query($sql) or die(mysql_error());
     echo $sql;

    if(mysql_num_rows($result) == 1)
    {
         $row = mysql_fetch_array($result);
        $acc = $row['account'];

        $_SESSION['username'] = $username;
        $_SESSION['account'] = $acc;
        $_SESSION['loggedin'] = 1;

         echo "<h1>Success</h1>";
        echo "<meta http-equiv='refresh' content='=2;panel.php' />";
    }
    else
    {
         echo "<h1>Error</h1>";
        echo "<p>Please <a href=\"login.php\">click here to try again</a>.</p>";
    }
}
else
{
    ?>



    <form method="post" action="login.php" name="loginform" id="loginform">
    <fieldset>
        <label for="username">Username:</label><input type="text" name="username" id="username" /><br />
        <label for="password">Password:</label><input type="password" name="password" id="password" /><br />
        <input type="submit" name="login" id="login" value="Login" />
    </fieldset>
    </form>

   <?php
}
?>

我的退出文件

<?php
$_SESSION = array(); 
session_unset();
session_destroy();


echo "Logged Out !";
header("Location:login.php");

?>

问题是当我尝试注销会话时不会被破坏。当它重定向到登录页面时,它表示我已经登录。当用户点击注销时,如何完全破坏会话?

2 个答案:

答案 0 :(得分:21)

将您的退出更改为以下内容:

<?php
session_start(); # NOTE THE SESSION START
$_SESSION = array(); 
session_unset();
session_destroy();

// echo "Logged Out!";
// Note: Putting echo "Logged Out!" before sending the header could result in a "Headers already sent" warning and won't redirect your page to the login page - pointed out by @Treur - I didn't spot that one.. Thanks...
header("Location:login.php");
exit(); # NOTE THE EXIT
?>

在处理会话时,每个页面始终需要session_start()

exit()header()一起使用时,请务必Location页面,因为该页面将继续执行。

答案 1 :(得分:5)

我认为你在$ _SESSION = array()之前忘记了session_start();在您的注销脚本中