How can session timeouts be effectively implemented to handle browser closures in PHP applications?
Session timeouts can be effectively implemented in PHP applications by setting a session timeout value in the php.ini file or using the session_set_cookie_params() function to specify the expiration time for the session cookie. Additionally, you can check the session expiration time on each page load and redirect the user to a login page if the session has expired.
// Set session timeout to 30 minutes
ini_set('session.gc_maxlifetime', 1800);
// Set session cookie params to expire in 30 minutes
session_set_cookie_params(1800);
// Start the session
session_start();
// Check if session is expired
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
session_unset();
session_destroy();
header("Location: login.php");
exit();
}
// Update last activity time stamp
$_SESSION['LAST_ACTIVITY'] = time();