I have a js code that logs out only on tab close, using sessionStorage, but it was not as smooth as I would like
if (sessionStorage.getItem('reloaded') != null) {
console.log('page was reloaded');
} else {
console.log("page was closed");
fetch('logout.php', {
method: 'POST', // Use POST for sensitive actions like logout
headers: {
'Content-Type': 'application/x-www-form-urlencoded', // Content type
},
})
.then(response => {
if (response.ok) {
console.log('Logged out successfully');
window.location.replace("http://localhost/foodblog/index.php");
} else {
console.log('Logout failed');
}
})
.catch(error => {
console.error('Error during logout:', error);
});
}
sessionStorage.setItem('reloaded', 'yes');
this would show a redirect on page load, I think it looks kinda bad, also I tried using
the “unload” event listener:
window.addEventListener('unload', function () {
navigator.sendBeacon('logout.php');
});
this works perfectly fine, but unload is deprecated, any idea how to improve this?
logout.php:
<?php
session_start();
if(isset($_SESSION["user_id"])){
unset($_SESSION["user_id"]);
}
if(isset($_SESSION["username"])){
unset($_SESSION["username"]);
}
session_destroy();
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time() - 3600, '/');
}
header("Location: index.php");
exit();
?>
1
You cannot reliably have a signal from the client device back to the server to signify the end of a session. That’s just how browsers/HTTP/networks in general work.
If you want the client browser to toss the session cookie when the browser/tab is closed, just set the cookie expiration to zero, and the browser will do it for you.
Server-side, if you have data that needs to be cleared or tasks that need to be executed for ended sessions, then you need to decide on what period of time passes without interaction before you declare a session “over” and have a periodic job that takes care of that.
That said, given the contents of your logout.php
you don’t need to do anything other than session_destroy()
for an intentional logout. For an implicit logout you can just rely on the session.gc_maxlifetime
setting.