3

I'm trying to understand when a PHP session will timeout and force the user to log back in again.

When the user first logs in to the site successfully I'm setting a session global like this:

$_SESSION['AcmeAuthenticated'] = TRUE;

On every other page I check at the top of the page for this:

if (!isset($_SESSION['AcmeAuthenticated']) and $_SESSION['AcmeAuthenticated'] !== TRUE) {
 header('Location: index.php');
 die;
}

I've noticed during development that I can keep my browser open all day and it won't ask me to login again. If I quit the browser then it will prompt me to login again. I checked the PHP info and session.gc_maxlifetime is set to 900 - I took that to mean that the PHP session would end in 15 minutes?

I'm new to PHP so still trying to learn how sessions work and when the timeout comes into effect.

user982124
  • 4,416
  • 16
  • 65
  • 140

3 Answers3

0

if statement should be:

if(!isset($_SESSION['AcmeAuthenticated']) && $_SESSION['AcmeAuthenticated'] !== true)
{
    header('Location: index.php');
    die;
}

you should need to use && instead of and. feel free to use session_set_cookie_params() to manipulate the session cookie params, but it sounds like your cookie is a 'session' cookie; that would be why it disappears after browser close.

Jon B
  • 497
  • 1
  • 9
  • 25
0

When you exit your browser, it will clear all SESSIONS. That is why you always have to relogin every time you exit your browser. However, yes, you can set how long you want the SESSION to last for. It shows you how here: How do I expire a PHP session after 30 minutes?

Community
  • 1
  • 1
frosty
  • 2,559
  • 8
  • 37
  • 73
  • This is a lore which is not necessarily true. It depends on whether the session is handled by cookie or via query string, on cookie lifetime and whether the client removes cookies when it is closed (which is client side configuration and out of your control).Some sites update frequently via AJAX, so on every refresh the session timeout is reset, but that functionality will not be not present after the browser window is closed, so the session will expire then. – syck Dec 10 '15 at 15:41
  • @syck Dude, are you browsing my answers are something? – frosty Dec 10 '15 at 19:28
  • Only one. When I read that you think that indentation makes a script less readable, I was interested on how much programming experience you may actually have. – syck Dec 11 '15 at 13:55
  • @syck Dude. That's just personal preference. Why are you being so obstinate? – frosty Dec 11 '15 at 20:56
0

PHP sessions end when the browser window is closed [1].

Yeah, session.gc_maxlifetime is set in seconds, so 900 is 15 minutes. You probably want to bump that up to about 30,000 (about 8 hours).

John Doe
  • 905
  • 8
  • 9