开发者

PHP Session timeout, problem with code

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();
    }
    ?


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.


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜