How to check session timeout?

If user already login and go to member section. If he leave computer for long time without logout.

If he click any link in member section again. I want to display message to tell him that session timeout. you must login again

How can I check?

Create a timestamp when the user enters the section. when he re-enters generate another one and compare it to the old one. If the difference is greater than a given value, destroy the session and throw him back to the login screen.

Thanks, Is php has any function to check it ?

The time() function returns the actual time in seconds.

I mean function about session to check directly because I use JSP before and jsp has method to check if current session is new session or old session.

you could try this code (I’ve not tested it). Put it at the top of your scripts.

if (!empty($_SESSION['enterTime'])) {
    $timeDiffernce = time() - $_SESSION['enterTime'];
    if ($timeDiffernce > 3600) { // exprie after one hour (3600 seconds)
        // unset session
        unset($_SESSION['username']);
        unset($_SESSION['password']);
        unset($_SESSION['enterTime']);

        // get login form

    } else {
        // Reset to current time.
        $_SESSION['enterTime'] = time();
    }
} else {
    $_SESSION['enterTime'] = time();
}

-Helge

I put this code at the top of every script

session_start();
        if(!session_is_registered("user"))
        {
                print "<script language='Javascript'>";
                print "window.location.replace('../membersignup/loginmail.php');";
                print "</script>";
                exit;
        }

When user login I register username as session variable, so every page I check this variable. if session timeout (26 minute). I use code to redirect to loginmail.php again.

This code should work. But the problem is I login and leave my computer more than 1 day.

When i click link again, it should redirect in to loginmail.php but session still valid so I still can surf member section. I don’t know why session not timeout ?

What’s your ‘register_globals’ setting?
If it’s set to off (as in more recent versions of PHP) you should not use session_register() anymore but instead use the $_SESSION array directly.

Do you destroy the session when a timeout occurs or just remove the ‘user’ variable from it?

The code that checks if a timeout has occured must be placed on top of every page you want to protect, too (with an include for example).

What’s your ‘register_globals’ setting?
If it’s set to off (as in more recent versions of PHP) you should not use session_register() anymore but instead use the $_SESSION array directly.

I use PHP 4.2.2 and set to off. but session_register() still work correctly.

Do you destroy the session when a timeout occurs or just remove the ‘user’ variable from it?

No, Doesn’t it automatic destroy when timeout?