Are there best practices for implementing an auto-logout feature in a PHP login script?

To implement an auto-logout feature in a PHP login script, you can set a session timeout period and check if the user's last activity was within that time frame. If not, you can destroy the session and log the user out automatically.

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

// Check if user's last activity was within the timeout period
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity']) > $timeout) {
    // Destroy the session and log the user out
    session_unset();
    session_destroy();
    // Redirect to the login page
    header("Location: login.php");
    exit;
}

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