how to log off automatically after the session has expired?

0

I'm having problems, if the user is idle for more than 24 minutes, the page remains the same. If I am on my page and the session is expired due to inactivity (it has passed 24 minutes), I still can interact on the page, but if I want to send the data (I send this data via ajax ), , the page asks to HTML again and all this data is lost.

Is there a way to unplug after the session has expired if the user has not interacted with the form? or some other approach that I can do?

public function run(){
    Session::init();

    $uname = $_POST['form-username'];
    $upass = $_POST['form-password'];
    $database = $this->db;
    $query = "
    SELECT * FROM tabela
    WHERE  BINARY  user_name=:user_name AND BINARY user_pass=:user_pass LIMIT 1";
    $stmt = $database->prepare($query);
    $stmt->execute(
        array(
            ':user_pass'=>$upass,
            ':user_name'=>$uname
        )
    );

    $resultado = $stmt->fetch();
    $contador = $stmt->rowCount() ;

    Session::set("loggedIn",false);
    if($contador > 0){
        Session::set("loggedIn",true);
        Session::set("id",$resultado['id']);
        header("location: ../outrapagina");
    } else {
        Session::set("mensagemErro","Login ou Senha Errada");
        header("location: ../login");
    }

}
    
asked by anonymous 10.06.2016 / 20:19

1 answer

3

A relatively simple method is to make an Ajax call of x in x minutes, to check if the session on the server side has already expired. If it has expired, you direct the visitor to the desired URL.

sessao_ativa.php

<?php
// iniciar sessão
session_start();

// se não existir a tua entrada de controlo ou a mesma for FALSE
if ( !isset($_SESSION["loggedIn"]) || !$_SESSION["loggedIn"] ) {
     echo "expirou";
}

// mata o script
die();

On your page the Ajax call:

$.get('sessao_ativa.php', function(data) {
     if( data == "expirou" ) {
         window.location.href = 'http://www.example.com';
     }
 });

To run the Ajax call, for example, every 60 seconds:

// executa código a cada 60 segundos e guarda ID do temporizador
var temporizador = setInterval(function() {
    // chamada ajax aqui
}, 60 * 1000);

// se precisares cancelar por algum motivo
clearInterval(temporizador);
    
11.06.2016 / 02:52