bubble_chart StackLab

User Sessions

8 steps · pending Not started · person_outline Guest
arrow_back Back

checkSessionTimeout()

Purpose: Automatically logs out a user after a period of inactivity.

code php
function checkSessionTimeout()
{
    global $pdo;

    // 10 seconds for testing
    // 1800 seconds = 30 minutes
    $timeout = 1800;

    if (isset($_SESSION['last_activity'])) {

        $inactive = time() - $_SESSION['last_activity'];

        if ($inactive >= $timeout) {

            endUserSession($pdo);

            session_unset();
            session_destroy();

            header(
                'Location: ' .
                BASE_URL .
                '/index.php?timeout=1'
            );

            exit;
        }
    }

    $_SESSION['last_activity'] = time();
}
Step by step:
  1. global $pdo; – Brings the PDO connection into scope (it's assumed to be defined outside this function).
  2. Sets $timeout to 1800 seconds (30 minutes). The comment mentions 10 seconds is used for testing.
  3. If last_activity exists in the session:
  4. Computes $inactive = time() - $_SESSION['last_activity'] If inactive ≥ timeout: Calls endUserSession($pdo) to close the DB record. Clears the PHP session with session_unset() and session_destroy() Redirects to the login page with a ?timeout=1 flag. exit stops further script execution.
  5. Always updates $_SESSION['last_activity'] to the current time so activity keeps the session alive.
In short: If the user has been idle longer than the timeout, close the DB session, destroy the PHP session, and redirect to login. Otherwise, refresh the activity timestamp.

login Sign in to save your progress permanently. info Progress is saved in your browser session
format_list_numbered Step 7 of 8