phpscrub
phpscrub

Reputation: 25

Session does not end properly

So normally my session should end when I press logout button on my page but when I go to the previous page via the button (top left). I just go back to my page logged in..

This is my login page code
<?php 

session_start();
$errors = array();
if(isset($_POST["name"]) and isset($_POST["password"])) {
    $conn = mysqli_connect("localhost", "root", "123", "whoosh") or die("No connection made: ".mysqli_connect_error());

    $name = $_POST["name"];
    $password = $_POST["password"];


    if (empty($name)) { array_push($errors, "Ename is required"); }
    if (empty($password)) { array_push($errors, "Password is required"); }

    if (count($errors) == 0) {
        $query = "SELECT * FROM tbl_user WHERE name='$name' AND password='$password'";
        $results = mysqli_query($conn, $query);
        $user = mysqli_fetch_assoc($results);

        if ($user) { // if user exists
        if ($user['name'] === $name and $user['password'] === $password) {
            $_SESSION['user'] = $user['id'];
            header('location: mainsite.php');
        }
    }


    }
}

?>

This is the code I put on my main site thats allows me to logout.
  <?php
    session_start();


   if(isset($_GET['logout'])){
     $_SESSION['name'] = null;
    header('Location:http://leopard.med.agfa.be/leopard/website/logIn.php');
   }

   session_destroy();
 ?>

So, why is my session not working properly and doesnt log out completely?

Upvotes: 1

Views: 140

Answers (2)

user1805543
user1805543

Reputation:

Try this one! I dont see any where you passing name to session.

if(isset($_GET['logout'])){
    // Initialize the session
       session_start();
    // Unset all of the session variables
       session_unset();
       $_SESSION = array();
    // Destroy the session.
        session_destroy();
        unset($_SESSION['user']);
    // Redirect to login page
        header('Location:http://leopard.med.agfa.be/leopard/website/logIn.php');
        exit();
}

Note: I used both unset() and destroy() functions you can use one.

Upvotes: 2

helderneves91
helderneves91

Reputation: 975

Change the logout script to this:

<?php

if(isset($_GET['logout'])){
    // null the _SESSION
    $_SESSION = null;
    // unset $_SESSION variable for the run-time 
    session_unset();
    // destroy session data in storage
    session_destroy();
    // last, redirect
    header('Location:http://leopard.med.agfa.be/leopard/website/logIn.php');
}

?>

Upvotes: 1

Related Questions