简体   繁体   中英

Unable to logout session in PHP

I tried a login and logout function in a signin bootstrap theme and it worked fine. But am not able to logout the session in my other tenplate when I use the same code which I used previously which worked. I tried all most all the solutions found in internet. I am getting a blank page when I click on Logout link.

login.php

<?php
session_start();
if (!empty($_SESSION['login_user'])) {
header('location:index.php');
}
?>
---html code---

<?php

define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_DATABASE', 'foodchain');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);

if($_SERVER["REQUEST_METHOD"] == "POST") {

  $myusername = mysqli_real_escape_string($db,$_POST['email']);
  $mypassword = mysqli_real_escape_string($db,$_POST['password']);


  $sql = "SELECT email,password FROM user_register WHERE email='$myusername' and password = '$mypassword'";
  $result = mysqli_query($db,$sql);
  $row = mysqli_fetch_array($result,MYSQL_ASSOC);


  $count = mysqli_num_rows($result);

  if($count == 1) {

   $_SESSION['login_user'] = $myusername;

    header('Location:index.php');
 }else {

     $logmsg = "Invalid Username or Password";


  }
}
?>

check_login.php

 <?php
 session_start();
  if (!isset($_SESSION['login_user']) || empty($_SESSION['login_user'])) {
 header('location:login.php');
 }
?> 

logout.php

<?php
 session_start();
 session_destroy();
 header("Location:login.php");
 die();
 ?> 

index.php

<?php
include('check_login.php');
?>

Its perfectly working when I don't use the template(downloaded from some website), or when I use the bootsrap signin template.

You really should provide us with some source code, links to things that you've tried, what you've previously tried, what errors you received, etc. From what I can gather, you're looking for a logout page using sessions? Here's what I've got.

<?php
session_start();
session_destroy();
header('Location: ..');
?>

The key part is setting $_SESSION to an empty array.

From http://php.net/manual/en/function.session-destroy.php :

<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();

// Unset all of the session variables.
$_SESSION = array();

// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
    );
}

// Finally, destroy the session.
session_destroy();
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM