bubble_chart StackLab

User Sessions

8 steps · pending Not started · person_outline Guest
arrow_back Back

endUserSession($pdo)

Purpose: Marks the current session as ended and calculates its duration.

code php
function endUserSession($pdo)
{
    if (!isset($_SESSION['session_id'])) {
        return false;
    }

    $session_id = $_SESSION['session_id'];

    $stmt = $pdo->prepare("
        UPDATE user_sessions
        SET
            session_end = NOW(),
            session_duration = TIMESTAMPDIFF(
                SECOND,
                session_start,
                NOW()
            )
        WHERE session_id = :session_id
    ");

    return $stmt->execute([
        'session_id' => $session_id
    ]);
}
Step by step:
  1. Guard clause – If $_SESSION['session_id'] isn't set, there's nothing to end, so it returns false.
  2. Reads the session ID from the PHP session.
  3. Prepares an UPDATE on user_sessions:
  4. session_end = current time (NOW()) session_duration = difference in seconds between session_start and NOW(), using MySQL's TIMESTAMPDIFF.
  5. Filters by session_id so only the current row is updated.
  6. Returns the result of execute() (a boolean: true on success, false on failure).
In short: Closes the current session row in the DB and stores how long it lasted.

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