How can PHP developers implement a timeout feature to automatically log out inactive users in a forum setting?

To automatically log out inactive users in a forum setting, PHP developers can implement a timeout feature by tracking user activity timestamps and comparing them against a predefined timeout period. If a user has been inactive for longer than the timeout period, they can be automatically logged out to enhance security and free up resources.

// Start session
session_start();

// Define timeout period (e.g. 30 minutes)
$timeout = 1800; // 30 minutes in seconds

// Check if user is logged in and there is a last activity timestamp
if(isset($_SESSION['user_id']) && isset($_SESSION['last_activity'])) {
    // Calculate time difference between current time and last activity
    $inactive_time = time() - $_SESSION['last_activity'];
    
    // If inactive time exceeds timeout period, log user out
    if($inactive_time > $timeout) {
        session_unset();
        session_destroy();
        header("Location: logout.php");
        exit();
    }
}

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