0

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?

user2008726
  • 63
  • 2
  • 5
  • 2
    You will need to fire an AJAX request every 10 seconds to check this. – fire Nov 01 '13 at 13:51
  • every 8.. You can late for refresh session's lifetime. – Alex Kapustin Nov 01 '13 at 13:54
  • @fire You would need to set a timeout after every action (activity) in javascript, clear it when the user does something and only fire the ajax request when the timer runs out and you want to destroy the session. – jeroen Nov 01 '13 at 13:54

2 Answers2

0

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>
user2008726
  • 63
  • 2
  • 5
-1

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.

Unset session after some time

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.

Community
  • 1
  • 1
Hunter Mitchell
  • 7,063
  • 18
  • 69
  • 116