endUserSession($pdo)
Purpose: Marks the current session as ended and calculates its duration.
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
]);
}
- Guard clause – If
$_SESSION['session_id']isn't set, there's nothing to end, so it returnsfalse. - Reads the session ID from the PHP session.
- Prepares an UPDATE on
user_sessions: - Filters by
session_idso only the current row is updated. - Returns the result of
execute()(a boolean:trueon success,falseon failure).
session_end = current time (NOW())
session_duration = difference in seconds between session_start and NOW(), using MySQL's TIMESTAMPDIFF.
Sign in to save your progress permanently.
Progress is saved in your browser session
Step 4 of 8