How can you automatically log out a user after a certain period of inactivity in a PHP session?
To automatically log out a user after a certain period of inactivity in a PHP session, you can set a timeout value in the session and check the last activity time against the current time on each page load. If the difference exceeds the timeout value, you can destroy the session and redirect the user to the login page.
// Start the session
session_start();
// Set the timeout value in seconds
$timeout = 1800; // 30 minutes
// Check if last activity time is set
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity']) > $timeout) {
// Destroy the session
session_unset();
session_destroy();
// Redirect to the login page
header("Location: login.php");
exit;
}
// Update last activity time
$_SESSION['last_activity'] = time();