How can I make the session stay active all the time, unless the user closes it?
I give an example of how I do it.
I did this to achieve that, but it doesn't seem to work:
session_start();
if ($_SESSION['user'] !== false) {
setCookie("session", $_SESSION['user'], time()+365*24*60*60);
}
And when closing session:
setCookie("session", $_SESSION['user'], time()-365*24*60*60);
The function
session_start
is what creates and maintains the session. The internal information of the session should not be passed in cookies (session_start
it is already in charge of sending a cookie with asession_id
for that).To increase the times you have to pass options to
session_start
.In the example the sessions last one day
cookie_lifetime
is used to indicate the life of the cookie that contains thesession_id
and withgc_maxlifetime
the cleaning time of thesession_id
within the server.Regarding the validation of the sessions
Sessions with
session_start
are created when the function is called and are active even if the user is not logged in (or authenticated). It is your responsibility to record within the session data (eg$_SESSION['user']
and/or$_SESSION['rol']
, etc) the information about whether the user is logged in or not, who they are, what permissions they had at the time of logging in, etc.Putting that information in cookies is not advisable.