What are the best practices for managing session IDs and user sessions when a browser window is closed in PHP?
When a browser window is closed, the session ID and user session in PHP may still exist on the server, leading to potential security risks. To manage this, it is recommended to implement session timeout mechanisms and properly destroy the session when the browser window is closed.
// Set session timeout to 30 minutes
ini_set('session.gc_maxlifetime', 1800);
session_start();
// Check if session exists and if it's expired
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
session_unset();
session_destroy();
}
// Update last activity time
$_SESSION['LAST_ACTIVITY'] = time();