开发者

Logout problem /session not destroyed

开发者 https://www.devze.com 2023-01-03 17:21 出处:网络
I am having a problem when trying to login.. below is my code for the login <?php session_start(); include(\"functions.php\");

I am having a problem when trying to login.. below is my code for the login

<?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($_POS开发者_开发百科T['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
}
?>

My logout file

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


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

?>

The problem is that when i try to logout the session is not destroyed. When it redirects to the login page it says that im already logged in. How can i completely destroy the session when the users clicks on logout?


change your logout to the following:

<?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
?>

The session_start() is always require for each page when dealing with sessions.

Make sure you exit() the page when using header() with Location as the page will continue to execute.


I think you forgotten the session_start() before $_SESSION = array(); in your logout script

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号