getSessionDuration($pdo)
Purpose: Returns the duration of the current session in seconds.
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();
}
- Guard clause – If no
session_idis in the PHP session, returns0. - Reads the session ID.
- Prepares a SELECT that computes the duration using TIMESTAMPDIFF(SECOND, ...): From
- Executes and fetches a single column with
fetchColumn(). - Casts to
intand returns it.
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.
Sign in to save your progress permanently.
Progress is saved in your browser session
Step 5 of 8