0

I'd like to know how to keep the user logged in indefinitely, until they click the logout button. Currently I have a session variable loggedin that checks whether the user is logged in, but session variables expire after some time. How do I keep the user logged in indefinitely?

JorensM
  • 330
  • 4
  • 15
  • 1
    PHP Sessions explained here, you'll find your answer: [How do i expire a PHP session](https://stackoverflow.com/questions/520237/how-do-i-expire-a-php-session-after-30-minutes/1270960#1270960) – slashroot Dec 04 '21 at 12:49
  • @slashroot That's not quite what I'm looking for. I need to keep the user logged in INDEFINITELY, not for a specified amount of time. I want the user to be logged in forever or until they click the logout button. Is setting session expiration time to a very big number a good approach? – JorensM Dec 04 '21 at 13:11

1 Answers1

2

You can use a cookie for this. When the user logging in for the first time, set a cookie for maybe 10 years. Then, when the user navigates the pages, update/reset the cookie to a further 10 years.

setcookie(
  "CookieName",
  "CookieValue",
  time() + (10 * 365 * 24 * 60 * 60)
);

Setting a Cookie in PHP

And when the user comes back to the site after some time, check if the cookie is available. If available, you can log them in automatically, if not, redirect to the login page.

if(isset($_COOKIE['CookieName'])){
    $cookie = $_COOKIE['CookieName'];
}
else{
    // No Cookie found - Redirect to Login
}

You can use two cookies for user name and password(encrypted).

Dula
  • 1,276
  • 5
  • 14
  • 23
  • I think the question is about the automatic session timeout on the server side (gc_maxlifetime being usually 24 or 30 minutes). – lukas.j Dec 04 '21 at 15:01
  • Yes, and I do not think and know a way to make the server remember a user session indefinitely. I think this an alternate way to achieve the goal. – Dula Dec 04 '21 at 15:07