How do I correctly remove the user after a downtime?

2

ANSWER

Below is the answer for anyone who has experienced something like this. First I created an extra field in my table called ActiveTime where I store the time () as soon as the user logs in. See below:

$tempoAtivo = time() + 30;

After storing, I created a new file called online that works as follows:

 <script>
setInterval(function(){
    $("#verOnline").load(location.href+" #verOnline");
    }, 2000);
</script>
<div id="verOnline">
<?php
$tempoAtual = time();
    $tempoAtivo = time() + 30;
       $alterar = mysqli_query($conexao,"UPDATE proj_acessos SET Tempo = '".$tempoAtivo."' WHERE IdUsuarios = ".$_SESSION['IdUsuarios']."");
     $alterar = mysqli_query($conexao,"UPDATE proj_acessos SET StatusOnline = 'N' WHERE Tempo < ".$tempoAtual."");
?>
</div>

The code above updates the database with the active time of the user every 2 minutes. If the user leaves the system directly through the browser, the time to update in the database and when the current time is greater than the time in the database, the status changes to offline.

    
asked by anonymous 05.05.2015 / 17:17

2 answers

3

You'll have to do something like this:

if (empty($_SESSION)) session_start();

if (empty($_SESSION['lastAccess'])) $_SESSION['lastAccess'] = time();
else {
    $_SESSION['lastAccess'] -= time();
}

if ($_SESSION['lastAccess'] > time()+5) {
    session_destroy();
    echo('session timeout');
}

Explaining:
If there is no session, start one;
If there is no "last access" then the last access is equal to now;
Or, take the now to the time of the last access
if the last access is greater than 5 seconds now, then the session has expired

This is a bit pseudo-code that I no longer have a PHP environment to test the code

As for the second question, someone in the English SO has a wonderful answer

    
05.05.2015 / 17:40
2

php code is only executed once when the page loads.

This does nothing:

if($segundos > $limite){
    session_destroy();
    echo "<script>alert('Sua sessão acabou!'); window.location.href='../index.php';</script>";
}else{
    $_SESSION['Time'] = time();
}

Unless the $ second variable is greater than the $ limit when the script is run, or if the page is constantly being refreshed (something you should not do).

This validation should be client-side in javascript.

    
05.05.2015 / 17:25