I am using this code to end session after 10 seconds of inactivity:
ini_set('session.gc_maxlifetime', 10);
session_start();
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 10)) {
session_unset();
session_destroy();
}
$_SESSION['LAST_ACTIVITY'] = time();
It's works only when I refresh page after 10 seconds of inactivity. If I not refresh page or close my browser the session will never be destroyed. Could someone help me how to fix this?
After 10 seconds, you need to destroy the session, then redirect them, like this:
session_destroy();
header("Location: logoutpage.php");
This will "refresh" the page and destroy the session.
Sorry about me not clarifying, but you will need an ajax call, here is a similar question. I will post the ajax in a moment. Sorry.
here is the ajax...set the timeout to your specified time. Again, sorry for not clarifying.
function refresh() {
$.ajax({
type: 'GET', // can be POST or GET
url: 'page.php' // php script to call
// when the server responds
}).done(function(response) {
console.log(response);
// call your function automatically
setTimeout(refresh, 5000);
});
}
Basically, the function refresh
get called every 5000 milliseconds.
Thanks for advices.
Now I am using also this javascript code to refresh after 10 seconds of inactive and it works good. But when I close browser session still will not be destroyed.
<body onmousemove = "canceltimer()"; onclick = "canceltimer()">
<script type="text/javascript">
var tim = 0;
function reload () {
tim = setTimeout("location.reload(true);",10000);
}
function canceltimer() {
window.clearTimeout(tim);
reload();
}
</script>