Make session expire after 5 minutes of inactivity

Hello, I'm lost in this logic, I'm using codeigniter, and I'm trying to expire the session after 5 minutes of inactivade (if the user is without accessing the page for up to 5 minutes), I arranged the code, and created a logic with ajax, as soon as the user logs in I write the team in the database]}

D testdata ['last_activity'] = time()+(5 * 60);

In the table of my bank session I record the team in the field ultima_activity, and I check with ajax from 1 to 1 minute querying the controller Area_usuario the time of the last session Activity:

$lastVisitTime = $_SESSION ['last_visited'];

And compare with the team recorded in the bank ultima_activity, and if it is less than or equal to the last team recorded in the bank I give an update in the bank increasing the team, until beauty, I did the code it is updating the team in the Bank of 1 in 1 minute, and nothing works, even if I leave from 5 minutes it does not run the expiration, I do not know what ta happening if you can help me thank you.

My code is like this, this is my controler Area_usuario:

 //verificar inatividade de sessão
      public function verificarInatividade()
      {
          $vetor = $_SESSION['usuarioLogado'];
          $email = $vetor->email; 
           
           //pego a ultima atividade que eu gravei na session;     
           $lastVisitTime  = $_SESSION['last_visited'];        
             
            //verifico o time gravado no tempo  
            $verificar =  $this->login_cliente_model->checarTempoSession($email);
            $cincominutos = $verificar->ultima_atividade;
          
          //veririco se o tempo inativo é menor ou igual ao gravado no banco
          if ($lastVisitTime <= $cincominutos) {  
                  
                  //se for ele faz o update pra mudar a ultima atividade do banco
                  $ultima_atividade = time()+(5 * 60);
                  $this->login_cliente_model->updateSession($ultima_atividade, $email);
                  
                  $retorno['erro'] = 0;
                  $retorno['msg']  = 'Ativo';
                  $retorno['verificarSessao']  =  $lastVisitTime;

                  header('Content-Type: application/json');
                  echo json_encode($retorno);
                  exit;

              } else {

                  //se não ele exclui a sessão aberta no banco e vai pra função logout 
                 $checharSessi = $this->login_cliente_model->checarSession($email);
              
                if($checharSessi  != FALSE){
                 
                   $this->login_cliente_model->deletarSession($email); 
                }
                
                  $retorno['erro'] = 60;
                  $retorno['msg']  = 'Inativo';
                  $retorno['verificarSessao']  = $lastVisitTime;

                  header('Content-Type: application/json');
                  echo json_encode($retorno);
                  exit;
          }

      }
      //verificar tempo de sessao
      public function expiraSessao()
      {
           if ($this->session->userdata('usuarioLogado')) {
           
                  $retorno['erro'] = 0;
                  $retorno['msg']  = 'Sessão expirou, acesse novamente.';
                  $retorno['verificarSessao']  =  '0';

                  header('Content-Type: application/json');
                  echo json_encode($retorno);
                  exit;
             
           }
             

      }

Here My ajax that does the check:

//Verificar inatividade na session
        var verificarInatividade= function (tempoParaChecarNovamenteEmSegundos) {
        $.ajax({
            type:"GET",
            url:"localhost/area_usuario/verificarInatividade", 
            dataType: "json",
            success: function (resposta){
            
            if (resposta.erro === 0) {  
                
                   var url = resposta.verificarUsuario;
                   console.log(url);
                    setTimeout(function() { verificarInatividade(tempoParaChecarNovamenteEmSegundos); }, tempoParaChecarNovamenteEmSegundos * 60000);
            } else {
                   
                      expiraSessao();
                     console.log(url);
                    setTimeout(function() { verificarInatividade(tempoParaChecarNovamenteEmSegundos); }, tempoParaChecarNovamenteEmSegundos * 60000);
            }  

            },
            error:function(){
                console.log(resposta);
            }
        });
        }

   //expira sessão    
        var expiraSessao= function() {
            $.ajax({
                type:"GET",
                url:"localhost/area_usuario/expiraSessao", 
                dataType: "json",
                success: function (resposta){
                   
                    window.location.replace("localhost/login_usuario/sessao_expirada");
                   
                },
                error:function(){
                    console.log(resposta);
                }
            });
        }

Now I log in and even if I leave the window inactive for more than 5 minutes, it keeps updating the team in the bank and does not expire the session, and it should expire if the session is inactive for 5 minutes, I do not know why he is acting like this, I have reviewed this code more than a thousand times, if you can help me by giving me a light, I am grateful.

Author: Joana, 2020-09-16

1 answers

The best solution is to implement your own session timeout. Use a simple timestamp that indicates the time of the last activity (i.e. Request) and update it with each request:

if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
    // last request was more than 30 minutes ago
    session_unset();     // unset $_SESSION variable for the run-time 
    session_destroy();   // destroy session data in storage
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp

Updating session data with each request also changes the session file modification date so that the session is not removed by the garbage collector prematurely.

You can also use an additional timestamp to generate again the session ID periodically to prevent attacks on sessions such as session pinning:

if (!isset($_SESSION['CREATED'])) {
    $_SESSION['CREATED'] = time();
} else if (time() - $_SESSION['CREATED'] > 1800) {
    // session started more than 30 minutes ago
    session_regenerate_id(true);    // change session ID for the current session and invalidate old session ID
    $_SESSION['CREATED'] = time();  // update creation time
 1
Author: biel silva, 2020-09-17 03:08:39