What are the best practices for tracking session duration and user activity in PHP applications?

To track session duration and user activity in PHP applications, you can use session variables to store timestamps of when the session started and when the user last accessed the application. By comparing these timestamps, you can calculate the session duration and track user activity.

// Start or resume the session
session_start();

// Set the session start time if it's not already set
if (!isset($_SESSION['start_time'])) {
    $_SESSION['start_time'] = time();
}

// Update the last access time
$_SESSION['last_access_time'] = time();

// Calculate session duration
$session_duration = $_SESSION['last_access_time'] - $_SESSION['start_time'];

// Track user activity
$user_activity = "User was active for " . $session_duration . " seconds.";

// Output session duration and user activity
echo $user_activity;