How to avoid user logout when closing browser with PHP?

3

I currently use SESSION . When I close the browser, it disconnects. How can I make a login at click on Continue connected, the user does not disconnect after closing?

    
asked by anonymous 02.12.2017 / 17:05

2 answers

4

Every session is a cookie, but the cookie data is saved on the server instead of the browser, the cookie of a session is like a token

You can use session_set_cookie_params

void session_set_cookie_params ( int $lifetime [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]] )
Setting the lifetime will increase the time of the session, because technically it is impossible to create an infinite session.

What would look like this:

session_set_cookie_params(<tempo em segundos>);
session_start();

However it does not update after the Cookie is created, so you may have to use setcookie :

session_set_cookie_params(<tempo de vida>);
session_start();
setcookie(session_name(), session_id(), time() + <tempo de vida>, '/');

You can also implement simple Ajax to run a small script, just to keep the session:

session.php

<?php

$tempodevida = 2678400; // 1 ano de vida
session_set_cookie_params($tempodevida);
session_start();
setcookie(session_name(), session_id(), time() + $tempodevida, '/');

Ajax with JavaScript:

(function sessao() {
    var oReq = new XMLHttpRequest();
    oReq.open("GET", "sessao.php", true);
    oReq.onload = function () {
        //Após o Ajax terminar a requisição executará daqui 5 segundos
        setTimeout(sessao, 5000);
    };
    oReq.send(null);
})();//Auto executa

With jQuery:

(function sessao() {
    $.ajax("sessao.php").then(function () {
        //Após o Ajax terminar a requisição executará daqui 5 segundos
        setTimeout(sessao, 5000);
    });
})();//Auto executa

However I need to make it clear that this will not affect session.gc_maxlifetime , as this is resolved in the backend by PHP itself, you can even try to extend the time by changing php.ini this line:

session.gc_maxlifetime=coloque aqui o tempo limite;

Yet this will affect all sessions, which will not always be what you want.

How the browser interprets with session_set_cookie_params and without

Not setting session_set_cookie_params :

Withsession_set_cookie_params:

That is, when Expires / Max-age is equal to Session means that when the browser is closed and reopened this cookie will no longer exist, but when set the cookie lifetime you have a date to expire and every time you use the session the time will be updated.

    
02.12.2017 / 17:46
1

Placing a cookie. In these cases I put the cookie with any value (I usually use uniqid) and saved in the database with the IP of the guy, so I do not take the risk. Every time it opens I check if the cookie exists and search the database for the cookie to check the current IP with the IP that is in the database.

    
02.12.2017 / 17:34