I have created a simple login page which is based on the sessions.
session_start();
and added a logout page that contains this
If the session exists, log out by destroying the session and redirecting the user to the home page. A temporary cookie was used to store the session identity. This cookie is also destroyed.
<?php
// This is the logout page for the site.
session_start();//access the current session.
//if no session variable then redirect the user
if (!isset($_SESSION['user_id'])) {
header("location:index.php");
exit();
}else{ //cancel the session
$_SESSION = array(); // Destroy the variables
session_destroy(); // Destroy the session
setcookie('PHPSESSID', ", time()-3600,'/', ", 0, 0);//Destroy the cookie
header("location:index.php");
exit();
}
?>
You will only be able to detect if the browser window has been closed using javascript at which point you might be able to trigger an Ajax request to perform a logout action.
to remove session variables - session_unset();
to destroy the session - session_destroy();
session_unset();
session_destroy();
Server can't detect browser or tab closed, you could use Javascript or Ajax but sorry I don't have knowledge about that.
My suggestion is use Session Timeout, so session will be destroyed if there's no action from user. This is an example :
// destroy every 2 minutes
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 120)) {
// last request was more than 2 minutes ago
session_destroy(); // destroy session data in storage
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
// end of code
Hope this help you
if you use:
session_set_cookie_params(0);
session_start();
Your session cookie will destroy when the browser is closed... so your session will be good until they close the browser. IE. You login, and you are logged in, you close the browser, re-open it, go to the site again, and you wont be logged in.