Search code examples
phpsessionsession-cookiesdestroy

session_destroy cannot destroy session php


I have login and logout pages but cannot logout always says the user already logged-in. Here is my login page:

<?php


 session_start();
  include_once("connection.php");
  if(isset($_POST) & !empty($_POST)) {
    $userName = mysqli_real_escape_string($connection, $_POST['userName']);
    $userPassword = md5($_POST['userPassword']);
    $login = "SELECT * FROM `users` WHERE userName = '$userName' and password = '$userPassword'";
    $result = $connection->query($login);
    while ($val = mysqli_fetch_array($result))
    {
        $isAdmin    = $val['isAdmin'];
        $companyID  = $val['companyID'];
        $branchID   = $val['branchID'];
        $ID         = $val['ID'];
    }
    $count = mysqli_num_rows($result);
    if($count == 1){
      $_SESSION['userName'] = $userName;
      setcookie("userID", $ID);
      setcookie("companyID", $companyID);
      setcookie("branchID", $branchID);
      if(!$isAdmin){
        header('location: home.php');
      }
      else {
        header('location: admin/home.php');
      }
    }
    else {
      $fmsg = "Wrong user name";
    }
  }
  if(isset($_SESSION['userName'])){
    $smsg = "Already loggedin";
  }
?>

Here is loggout page:

<?php
  session_start();
  session_destroy();
  unset($_COOKIE['companyID']);
  unset($_COOKIE['userID']);
  unset($_COOKIE['branchID']);
  setcookie('companyID', null, -1, '/');
  setcookie('userID', null, -1, '/');
  setcookie('branchID', null, -1, '/');
  header('location: index.php');
?>

How could I solve this? Could anyone help me? Also there is an attached image show cookies.enter image description here


Solution

  • Just use this:

    $_SESSION = array();  
    session_destroy();