Jump to content

Session was not destroy even after logging out


genzedu777

Recommended Posts

Hi all,

 

My session is not destroy even after I have click 'log out'

 

The user will only log out only when I have closed the browser. May I know what could have caused the problem?

Below is my code

 

My admin.php page

<?php
// For logging out
    if (isset($_SESSION['username'])) {
	echo '<a href="admin_logout.php">Log Out (' . $_SESSION['username'] . ')</a>';

	// Connect to the database 
	$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); 

	// Retrieve the user data from MySQL
	$query = "SELECT tutor_id, name FROM tutor_profile ORDER BY name ASC";
	$data = mysqli_query($dbc, $query);

  
	// Loop through the array of user data, formatting it as HTML
	echo '<h4>Latest members:</h4>';
	echo '<table>';
	while ($row = mysqli_fetch_array($data)) {
			echo '<td><a href="viewprofile.php?tutor_id=' . $row['tutor_id'] . '">' . $row['name'] . '</a></td></tr>';
	}
	echo '</table>';

	mysqli_close($dbc);
}
else {
	echo '<a href="admin_login.php">Log In</a>';
}
?>

 

 

My logout.php page

<?php
  // If the user is logged in, delete the session vars to log them out
  session_start();
  if (isset($_SESSION['admin_id'])) {
    // Delete the session vars by clearing the $_SESSION array
    $_SESSION = array();

    // Delete the session cookie by setting its expiration to an hour ago (3600)
    if (isset($_COOKIE[session_name()])) {
      setcookie(session_name(), '', time() - 3600);
    }

    // Destroy the session
    session_destroy();
  }

  // Delete the user ID and username cookies by setting their expirations to an hour ago (3600)
  setcookie('admin_id', '', time() - 3600);
  setcookie('username', '', time() - 3600);

  // Redirect to the home page
  $home_url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/admin_login.php';
  header('Location: ' . $home_url);
?>

Well on the logged in page you are determining whether or not a user is logged in based on the $_SESSION['username'] variable, but on the log out page, you are using the $_SESSION['admin_id'] to determine that. You should keep the login system consistent throughout.

 

Also I wouldn't store the admin_id and username in seperate cookies like that, I would store them in the session and so keep them on the server side.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.