bubble_chart StackLab

User Sessions

8 steps · pending Not started · person_outline Guest
arrow_back Back

How They Work Together

How They Work Together

code text
|         Function          |                                 Role                              |
|---------------------------|-------------------------------------------------------------------|
| `startUserSession`        | Called on login — creates a DB row, returns `session_id`.         |
| `getSessionDuration`      | Can be called anytime to report how long the session has lasted.  | 
| `hasActiveUserSession`    | Used to enforce single-session-per-user or detect stale sessions. |
| `endUserSession`          | Called on logout or timeout — closes the DB row.                  |
| `checkSessionTimeout`     | Called on each request — idle check + auto-logout.                |
Typical flow:
  1. User logs in → startUserSession($pdo) → store returned ID in $_SESSION['session_id'].
  2. On each page load → checkSessionTimeout() runs.
  3. If the user is idle too long → endUserSession($pdo) + destroy session + redirect.
  4. On manual logout → endUserSession($pdo) + destroy session.
  5. getSessionDuration($pdo) and hasActiveUserSession($pdo, $user_id) are utility/query functions used where needed.
  6. ---

    Minor Notes / Potential Improvements

    • checkSessionTimeout uses global $pdo — passing $pdo as a parameter (like the other functions) would be cleaner and more consistent.
    • startUserSession doesn't store the returned ID in $_SESSION['session_id'] itself — the caller must do it. Otherwise subsequent functions (endUserSession, getSessionDuration) won't work.
    • session_destroy() doesn't unset $_SESSION in all cases; session_unset() is called first here, which is correct.
    • BASE_URL must be defined elsewhere (e.g. a config file) for the redirect to work.

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