Implementing logoff on my login system with UNSET SESSION

1

I have the following login.php file:

<?php


require_once('conexao.php');

// FETCH DATA FROM FORM USING METHOD POST
// IF BUTTON NAME "LOGIN" IS SET
if (isset($_POST['login'])) {




// FETCH DATA FROM INPUT FIELD
$user = mysqli_real_escape_string($conexao, $_POST['usuario']);
$pass = mysqli_real_escape_string($conexao, $_POST['password']);

  // CHECK ALL FIELD HAS BEEN FILLED UP
 if ($user && $pass) {

   // QUERY FROM DATABASE
  $query= mysqli_query($conexao, "SELECT * FROM usuarios WHERE usuario='".$user."'");
  $checkuser= mysqli_num_rows($query);

   // CHECK IF USERNAME EXIST ON DATABASE
  if($checkuser != 1) {

    // I'LL BE SETTING A VARIABLE IF YOUR DOESN'T EXIST
   header("Location: ../login.php" . "?erro=3");
  }

   // FETCHING PASSWORD IN DATABASE WHERE USERNAME COINCIDES
  while ($row = mysqli_fetch_array($query)) {
   $checkpass= $row['senha'];


    // CHECK IF ENTERED PASSWORD MEETS THE USERNAME PASSWORD
   if ($pass== $checkpass) {

     // IF ALL OKAY SET SESSION
    setcookie("usuario", $user, time()+7200);
    $_SESSION['usuario'] = $user;
    $_SESSION['start'] = time();
    $_SESSION['expire'] = $_SESSION['start'] + (60 * 60 * 60);
    header("Location: ../admin.php");

    exit();
   } else {

     // SET VARIABLE THAT'LL SHOW IF USER PASSWORD IS INCORRECT

    header("Location: ../login.php" . "?erro=1");
   }
  }
 } else {

  // SET VARIABLE IF ALL FIELD ARE NOT FILLED UP

 header("Location: ../login.php" . "?erro=2");
 }
}


?>

The same is working OK, go to the panel, all right. However, inside the panel I have a "Logoff" button, which I wanted to return to the login screen and close the session. I read that it would be with UNSET. In case logout.php would only have one UNSET $ _SESSION ['user']? Another though I noticed in my code is that by changing the URL to admin.php the system takes the user to the panel without checking whether it is logged in or not.

    
asked by anonymous 05.09.2015 / 14:50

1 answer

2

To log out / redirect the user to a file named logout.php (for example).

Within this file use:

session_start(); // Pega a sessão que já foi iniciada
session_destroy(); // Cancela/Exclui a sessão iniciada
header('location: login.php'); //Redireciona para a pagina de login
    
05.09.2015 / 17:36