How can PHP developers handle situations where users leave the site without logging out, such as closing the browser?

When users leave the site without logging out, it can lead to security risks as their session remains active. To handle this situation, PHP developers can implement a session timeout mechanism that automatically logs out users after a certain period of inactivity. This can be achieved by setting a session timeout value and periodically checking the last activity time of the user.

// Set session timeout value (in seconds)
$session_timeout = 1800; // 30 minutes

// Check if user's last activity time is older than session timeout
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > $session_timeout)) {
    // Log out user
    session_unset();
    session_destroy();
    // Redirect to login page
    header("Location: login.php");
    exit;
}

// Update user's last activity time
$_SESSION['last_activity'] = time();