Skip to content
Advertisement

Automatically re-direct a user when session Times out or goes idle

I want to have a timer going to run every 3 minutes on the page (javascript), to detect if a php session ($_SESSION) has timed out… and if so, redirect them automatically.

A good example would be, a user logs in and runs up stairs, and never comes back down… I want the javascript to log them out with a simple redirect…

Is this possible? and how would I do such a thing? I am using PHP and JavaScript.

What Rob Kennedy said below is exactly what I am looking for:

…when the session times out, the browser should be told to navigate away from the current page. Some banks do this after a period of inactivity, for example.

Advertisement

Answer

You could use a simple meta refresh:

<meta http-equiv="refresh" content="180;url=http://example.com/logout" />

Or you implement a timeout with PHP:

session_start();
if (isset($_SESSION['LAST_REQUEST_TIME'])) {
    if (time() - $_SESSION['LAST_REQUEST_TIME'] > 180) {
        // session timed out, last request is longer than 3 minutes ago
        $_SESSION = array();
        session_destroy();
    }
}
$_SESSION['LAST_REQUEST_TIME'] = time();

Then you don’t need to check every 3 minutes if the session is still valid.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement