What are the best practices for handling session timeouts in PHP to ensure security and user experience?
Session timeouts are important for security as they help prevent unauthorized access to a user's session data. To ensure a good user experience, it's important to handle session timeouts gracefully by redirecting the user to a login page or displaying a message when their session expires.
// Set session timeout to 30 minutes
ini_set('session.gc_maxlifetime', 1800);
// Start the session
session_start();
// Check if the session is active
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
// Session expired, destroy session and redirect to login page
session_unset();
session_destroy();
header('Location: login.php');
exit;
}
// Update last activity time stamp
$_SESSION['LAST_ACTIVITY'] = time();