How can inactivity be tracked and used to automatically log out users in a PHP application?
To track user inactivity and automatically log them out in a PHP application, you can set a timeout period and compare the last activity timestamp with the current time. If the user has been inactive for longer than the timeout period, you can log them out by destroying their session.
// Start the session
session_start();
// Set the timeout period (in seconds)
$timeout = 1800; // 30 minutes
// Check if last activity timestamp is set
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > $timeout)) {
// Destroy the session and log the user out
session_unset();
session_destroy();
header("Location: login.php");
exit;
}
// Update last activity timestamp
$_SESSION['last_activity'] = time();