I've created a session to keep track of some user actions on a specific page.
When user navigates away from that specific page (but still on the same site), I need to reset the session.
I can set set timer for when session expires, but that's not what I want.
How can I reset session on page navigation?
Just make resetting the session the very first thing you do when loading a new page.
Do you have a single page that all traffic is routed through? If so you could do a simple check
if ($current_page != $session_page) {
$_SESSION = array();
}
If you don't have a single page all traffic goes through, then you will need to reset the session at the beginning of every other page.
$_SESSION = array();
Alternatively you can use
unset($_SESSION);
or
session_destroy();
Though note these handle slightly differently to the suggestions above. Note the second (session_destroy) will require you restart the session should you need it again.
You can never be sure that the session is really destroyed.
But there is an old trick used in for example chat applications where a "... is leaving" message is to be printed: On unload just open a popup windows with window.open()
that calls your logout page and then closes itself.
What I've done in the past is make a quick ajax call on unload to an unset page, much like the other answers on this page.
<script>
function myAjaxCall(){
//if using jquery
$.ajax('unset.php');
}
</script>
<body onunload="myAjaxCall()">