How can PHP developers ensure that session timeouts are properly enforced in an AJAX-driven application?
In an AJAX-driven application, PHP developers can ensure that session timeouts are properly enforced by setting a timestamp in the session when the user logs in and checking this timestamp on each AJAX request to see if the session has expired. If the session has expired, the user can be redirected to the login page.
// Start session
session_start();
// Set session timeout period in seconds
$session_timeout = 1800; // 30 minutes
// Check if user is logged in
if(isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true) {
// Check if session has expired
if(isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity']) > $session_timeout) {
// Session has expired, redirect to login page
header("Location: login.php");
exit();
}
// Update last activity timestamp
$_SESSION['last_activity'] = time();
} else {
// User is not logged in, redirect to login page
header("Location: login.php");
exit();
}