How can a PHP script automatically log out a user after a certain period of inactivity?
To automatically log out a user after a certain period of inactivity, we can store the user's last activity timestamp in a session variable. Then, on each page load, we can check if the time difference between the current time and the last activity timestamp exceeds our defined inactivity period. If it does, we can destroy the session and log the user out.
// Start the session
session_start();
// Define the inactivity period in seconds
$inactivity_period = 1800; // 30 minutes
// Check if the user is logged in and there is a last activity timestamp
if(isset($_SESSION['user_id']) && isset($_SESSION['last_activity'])) {
// Calculate the time difference
$current_time = time();
$last_activity_time = $_SESSION['last_activity'];
$time_diff = $current_time - $last_activity_time;
// Log the user out if inactive for too long
if($time_diff > $inactivity_period) {
session_destroy();
// Redirect to the login page or any other desired action
header("Location: login.php");
exit;
}
}
// Update the last activity timestamp
$_SESSION['last_activity'] = time();