What is the purpose of automatically logging out a user after a certain period of time in PHP?
Automatically logging out a user after a certain period of time helps to enhance security by reducing the risk of unauthorized access to the user's account if they leave their device unattended. This practice also helps to free up server resources by closing inactive sessions.
// Set the session timeout period to 30 minutes
ini_set('session.gc_maxlifetime', 1800);
session_start();
// Check if the user is logged in
if(isset($_SESSION['user_id'])) {
// Check if the last activity time is expired
if(isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > 1800)) {
// Log the user out and redirect to the login page
session_unset();
session_destroy();
header("Location: login.php");
exit;
}
// Update the last activity time
$_SESSION['last_activity'] = time();
}