What are the best practices for monitoring user activity and logout events in PHP applications when browser closure occurs?

When a user closes their browser without logging out of a PHP application, the server may not be notified of the logout event. To address this issue, you can implement a mechanism to monitor user activity and automatically log out users when their session expires or when the browser closure occurs.

// Check for user activity and logout if session has expired
session_start();

$timeout = 3600; // 1 hour timeout
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity']) > $timeout) {
    session_unset();
    session_destroy();
    // Redirect to logout page or perform any other necessary actions
}

$_SESSION['last_activity'] = time();