0

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();
    }
    ?
1
  • 1
    because the login time would always be less than time()+ anything!? Commented Jun 18, 2010 at 17:03

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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) { ... }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.