1

Hey guys i wanna check session of a logged in user in php dynamically.

I presently use:

$now = time();
if($now < $_SESSION['expire'])
{
//continue session
}
else
{
//exit
}

I would like to implement the same using javascript and dynamically check the variable every 60 secs. Is there a way to do this dynamically?

Yesh
  • 51
  • 10
  • You can use ajax to check the value of a php variable. – Manish Jangir Nov 28 '14 at 08:30
  • Take a look at this http://w3lessons.info/2014/01/01/how-to-check-expired-sessions-using-php-jquery-ajax/ – Hoijof Nov 28 '14 at 08:30
  • 1
    You cannot check a session variable at clientside. But if you know how long session expiry is, you can reset a "session access" variable, and assume the session expired when sufficient time expires after last "session access". However, checking with AJAX is probably not the solution, since each time you send an AJAX request, you refresh the session. – Amadan Nov 28 '14 at 08:31
  • i prefer not to go with ajax and with php/jquery/javascript. can u elaborate on how to do so? – Yesh Nov 28 '14 at 08:48
  • Better solution than ajax and js. http://stackoverflow.com/questions/520237/how-do-i-expire-a-php-session-after-30-minutes – Dhruv Kapatel Nov 28 '14 at 08:56
  • i currently use maxlifetime and cookies now i would like to prompt my user the session is going to expire. – Yesh Nov 28 '14 at 09:17

1 Answers1

2
<script type="text/javascript">
function checkSession() {
setInterval(function(){
     var now = Date.now();
     $.get('ajax.php?timestamp='+now,function(data){
        return true;
     });
},60000);
}
checkSession();
</script>

<?php 
    //In your ajax.php
    $timestamp = $_REQUEST['timestamp'];
    if($timestamp < $_SESSION['expire']) {
        //continue session
    } else {
        session_destroy();
    }
?>
Manish Jangir
  • 5,329
  • 4
  • 42
  • 75