How can a user be automatically logged out after a certain period of inactivity in a PHP application?

To automatically log out a user after a certain period of inactivity in a PHP application, you can set a session timeout value and check the last activity time of the user on each page load. If the user has been inactive for longer than the session timeout value, you can destroy the session and redirect them to the login page.

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

// Start or resume session
session_start();

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

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