How can developers implement automatic logout mechanisms based on session expiration in PHP applications, and what are the considerations for maintaining user security and privacy?
To implement automatic logout mechanisms based on session expiration in PHP applications, developers can set a session timeout value and regularly check if the session has expired. When the session expires, the user can be automatically logged out to ensure security and privacy.
// Set session timeout value (e.g., 30 minutes)
ini_set('session.gc_maxlifetime', 1800);
// Start the session
session_start();
// Check if the session has expired
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
session_unset();
session_destroy();
// Redirect to logout page or login page
header("Location: logout.php");
exit;
}
// Update last activity time stamp
$_SESSION['LAST_ACTIVITY'] = time();