views:

46

answers:

3

I have some code that will log the user out after x seconds of inactivity. The problem is that it logs them out before the time specified it doesn't even count the inactivity.

This is the code:

    <?php
    $_SESSION['loginTime'] = time();

    if($_SESSION['loginTime'] < time()+10*60){ 
         $error_msg ="Logged out due to inactivity";

 showLoginPasswordProtect($error_msg); 

session_destroy();
    }
    ?
A: 

You need to set $_SESSION['loginTime'] in a separate script, presumably after the user is authenticated.

Then in this script you need to figure out the difference between the session time and the current time, and then see if it is larger than your timeout threshold.

For example:

if( (time() - $_SESSION['loginTime'] ) > 10*60) { ... }
Justin Ethier
+1  A: 

Well $_SESSION['loginTime'] is the timestamp that they logged in (hopefully) which will always be less than the current timestamp, because you add one for every second. So you need to do this:

<?php

if($_SESSION['loginTime'] + 600 < time()){ 
    $error_msg ="Logged out due to inactivity";

    showLoginPasswordProtect($error_msg); 

    session_destroy();
}
?>

This way it will run the statement if 600 seconds have passed.

animuson
A: 

Look at what your script is doing:

  1. $_SESSION['loginTime'] = time();

... sets the 'loginTime' to the current time. Let's say the current time is '10'

  1. if($_SESSION['loginTime'] < time()+10*60)

... since we're assuming the current time is 10, then time()+10*60 becomes 10+10*60 = 610, and the if() becomes: if (10 < 610) {

So, your code will ALWAYS log out the user, since your logic is broken.

You need to set the loginTime ONCE, in the login script, instead of setting it each time, as you are now.

Marc B