How can time calculations be accurately performed and displayed when using sessions in PHP for tracking user interactions?

When using sessions in PHP for tracking user interactions, accurate time calculations can be performed by storing the initial timestamp when the session starts and then calculating the duration of the session by subtracting the initial timestamp from the current timestamp. This duration can then be displayed to the user to show how long they have been active on the site.

// Start the session
session_start();

// Store the initial timestamp when the session starts
if (!isset($_SESSION['start_time'])) {
    $_SESSION['start_time'] = time();
}

// Calculate the duration of the session
$duration = time() - $_SESSION['start_time'];

// Display the duration to the user
echo "You have been active for " . $duration . " seconds.";