What are the best practices for implementing an automatic logout feature in PHP to manage user inactivity in a live chat application?

To manage user inactivity in a live chat application, implementing an automatic logout feature in PHP is essential. This feature will help improve security by logging out users who have been inactive for a certain period of time, reducing the risk of unauthorized access to their accounts.

// Check user activity and logout if inactive for a certain period
session_start();

// Set the inactive timeout period (in seconds)
$inactive_timeout = 600; // 10 minutes

// Check if user is logged in and there is activity
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > $inactive_timeout)) {
    // Log out the user
    session_unset();
    session_destroy();
    header("Location: login.php"); // Redirect to login page
    exit;
}

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