Auto logout when browser close

Asked

Viewed 903 times

0

I use a Sqlite database to log in to check if the user exists. What I want to do is close the session when the browser window is closed. I have a tab that logs out if it is called.

$_SESSION = array();

if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
    );
}
session_destroy();      
  • There’s nothing to guarantee browser close the session. What is normally done is for the session to have an expiration time and to consider closed after that downtime. Anyway, I think it’s been answered. http://answall.com/questions/33867/realizar-a%C3%A7%C3%A3o-to-close-browser This doesn’t seem to be a PHP problem.

1 answer

0


If you want the session to close when it closes the window then use $_SESSION instead of $_COOKIE, now the session will only be destroyed when the entire Browser is closed and not just a tab.

What you can also do is use a timestamp, for example, after 5 minutes if the user tries to use the page the session will be expired, for that you need to save the timestamp in the session every time he loads any page, and then before saving the new timestamp check if the last load so far has passed 5 minutes

A rustic example:

php page.

<?php
    session_start();

    $tempo_limite_em_minutos = 5; // 5 minutos

    // se já foi definido vamos ver se a sessão ainda está valida
    if(isset($_SESSION['TEMPO'])){

        $tempo_desde_o_ultimo_carregamento = time() - $_SESSION['TEMPO'];
        if($tempo_desde_o_ultimo_carregamento / 60.0 > $tempo_limite_em_minutos){
            include 'logout.php';
            die();
        }

    }else{
        echo '<h1>Primeiro login</h1><br>';
    }

    // senão vamos apenas atualizar a sessão e mostra o conteudo que ele quer ver 
    $_SESSION['TEMPO'] = time();


echo '<h1>Você está logado</h1>
    <p>O php é uma ótima linguagem de programação, principalmente se você tem pouca memória no seu servidor</p>';

logout.php

<?php

    session_start();
    session_destroy();

    echo '<h1>Desculpe, a sua sessão expirou :/';

Browser other questions tagged

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