How can server-side PHP be used to automatically log out a user after a certain period of inactivity?

To automatically log out a user after a certain period of inactivity using server-side PHP, you can store a timestamp of the user's last activity in a session variable. Then, on every page load, you can check if the current time minus the last activity timestamp exceeds the desired inactivity period. If it does, you can destroy the session and log the user out.

session_start();

$inactive_time = 1800; // 30 minutes in seconds

if(isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > $inactive_time)) {
    session_unset();
    session_destroy();
    // Redirect to login page or any other desired action
}

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