How can PHP track user activity and log the time spent online, considering potential issues like closing the browser or navigating to a different URL?

One way to track user activity and log the time spent online in PHP is to use session variables to store the initial time when the user accesses the website and update it periodically. This way, even if the user closes the browser or navigates to a different URL, the session data will persist and allow you to calculate the time spent online accurately.

session_start();

if(!isset($_SESSION['start_time'])) {
    $_SESSION['start_time'] = time();
}

// Calculate time spent online
$current_time = time();
$time_spent = $current_time - $_SESSION['start_time'];

// Log time spent online
// Insert code here to log the time spent online in a database or file

// Update session start time
$_SESSION['start_time'] = $current_time;