How can automatic logout be implemented in PHP for users who have been inactive for a certain period of time?

To implement automatic logout for users who have been inactive for a certain period of time in PHP, you can store the user's last activity timestamp in a session variable. Then, on each page load, check if the difference between the current time and the last activity timestamp exceeds the desired inactive period. If it does, log the user out by destroying the session.

session_start();

$inactive = 1800; // 30 minutes in seconds

if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > $inactive)) {
    session_unset();
    session_destroy();
}

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