bubble_chart StackLab

User Sessions

8 steps · pending Not started · person_outline Guest
arrow_back Back

getSessionDuration($pdo)

Purpose: Returns the duration of the current session in seconds.

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

    $session_id = $_SESSION['session_id'];

    $stmt = $pdo->prepare("
        SELECT TIMESTAMPDIFF(
            SECOND,
            session_start,
            COALESCE(session_end, NOW())
        )
        FROM user_sessions
        WHERE session_id = :session_id
    ");

    $stmt->execute([
        'session_id' => $session_id
    ]);

    return (int) $stmt->fetchColumn();
}
Step by step:
  1. Guard clause – If no session_id is in the PHP session, returns 0.
  2. Reads the session ID.
  3. Prepares a SELECT that computes the duration using TIMESTAMPDIFF(SECOND, ...):
  4. From session_start To COALESCE(session_end, NOW()) — meaning: If the session has already ended (session_end is not NULL), use that. Otherwise use the current time (NOW()), i.e. the session is still active.
  5. Executes and fetches a single column with fetchColumn().
  6. Casts to int and returns it.
In short: Tells you how long the current session has been (or was) active, in seconds — works for both open and closed sessions.

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