How to avoid user logout when closing browser with PHP?
I currently use SESSION
. When I close the browser, it disconnects. How can I make a way to login by clicking Continue logged in, the user does not log out after closing?
2 answers
Every session is a cookie, but the cookie data is saved on the server instead of the browser, the cookie of a session is as if it were a token
You can use the session_set_cookie_params
void session_set_cookie_params ( int $lifetime [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]] )
Setting lifetime
will increase session time, as it is technically impossible to create an infinite session.
What would look like:
session_set_cookie_params(<tempo em segundos>);
session_start();
However it does not update after the Cookie has been 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 a simple Ajax to keep running a small script, just to keep the session:
Sessao.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 solved in the back-end 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;
Still it will affect all sessions, which will not always be what you want.
How the browser interprets with session_set_cookie_params and without
Without setting session_set_cookie_params
:
With session_set_cookie_params
:
That is, when Expires / Max-age is equal to Session
it means that when the browser is closed and opens again this cookie will cease to exist, but when the lifetime is set the cookie will have a date to expire and every time you use session the time will be updated.
Placing a cookie. In these cases I place the cookie with any value (usually I use uniqid) and saved in the database with the guy'S IP, so I do not take the risk. Every time it opens I check if the cookie exists and search the database the cookie to check the current IP with the IP that is in the database.