What are some best practices for implementing session timeouts in PHP for user authentication?
Session timeouts are important for user authentication to prevent unauthorized access to a user's account if they leave their session open. One way to implement session timeouts in PHP is by setting a specific time limit for the session to expire if there is no activity from the user. This can be achieved by checking the last activity time against the current time and destroying the session if the timeout limit is reached.
// Start the session
session_start();
// Set the session timeout limit in seconds
$timeout = 1800; // 30 minutes
// Check if the session variable for last activity time is set
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > $timeout)) {
// If the session is inactive for longer than the timeout limit, destroy the session
session_unset();
session_destroy();
}
// Update the last activity time in the session
$_SESSION['last_activity'] = time();