how to log off automatically after the session has expired?

Asked

Viewed 1,531 times

0

I am having problems, if the user is inactive for more than 24 minutes, the page remains the same. If I’m on my page and the session is expired due to inactivity (it’s past 24 minutes), I can still interact on the page, but if I want to send the data (I send this data via ajax) who were already half-populated in the HTML, the page asks to do log in again and all this data is lost.

Is there any way to unseal after the session has expired if the user has not interacted with the form? or some other approach I can make?

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");
    }

}
  • How are you doing to see if it’s past 24 minutes? Post your code so you can find the help you need.

  • I actually did not make any arrangements to check whether it passed the 24 minutes, rs.

  • Are you at least authenticating? How are you doing to authenticate?

  • Here you find an answer to expire in 30 minutes, I think it will help you

  • Otherwise, your question is too wide like this. I advise [Edit] to improve your chances of getting the answer you are looking for

  • I did an update

  • You can send ajax requests constantly to arrive if it is authenticated, or keep an open connection as a server, in which it constantly checks whether or not there is an active session, and when there is not, warns the client.

  • But I believe that this was going to consume a lot of resource. Maybe you should check this out when the user is going to interact with the page, or form. Like, if it starts to fill a field, you check and if necessary, drop.

  • You can also send a "Keep Alive" to prevent the session from expiring while the page is active in the browser. This can be every 20 min.

Show 4 more comments

1 answer

3

A relatively simple method is to perform an x-Ajax call in x minutes to verify that the server-side session has 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 so-called Ajax:

$.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);
  • How are you? It wasn’t me who said no, but I’d like to suggest you use the event .done (or "success":) jQuery combined with setTimeout, the use of setInterval the way you used can make multiple requests without one waiting for the other.

  • @Guilhermenascimento I only left an example that should be adapted to the reality of the OP code. Anyway, the setInterval works well for these scenarios... at least in the implementations I’ve been doing :) But there should only be one running, two or more and then yes, everything starts to get out of control and the browser dragging!

  • I worked on a chat system, which initially used the setInteval + ajax, with the flow of many users at the same time there have been unnecessary spikes on my server, apart from the conflicts of competing events that may occur, in case if a redirection probably does not occur, but any new implementation may be impaired. See you around!

  • @Guilhermenascimento Yes, what you say may occur, but notice that the PHP of this ajax call performs 1 task that takes micro-seconds to perform. Already the setInterval only runs every 60 seconds ;)

  • I do understand :), but imagine that there is a delay on your server due to some script with long execution, this will affect the front-end, the more users accessing so at a certain point there will be two or more events running at the same time, this I say only to one user, but it can occur in several in a period that users stay on average 10 minutes inside the site, then there will be more requests than normal, and may eventually occur peaks, especially if using some REST or database with mysql, postgresql, etc. This is just a suggestion ;)

  • @Guilhermenascimento We were here all night imagining scenarios ;) But as I said, I agree with you, although I only left a practical example. The question itself does not focus on a specific problem to solve, it gives to a universe of solutions... I left for the simplest that occurred to me!

  • I understand and I really have to agree, I was just afraid to even take such code to use in various situations, where the scenarios may occur that I thought, but really it is unlikely, thanks for the effort, I will leave +1 that because I believe it is a solution too.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.