How can the functionality of redirecting a user to a logout page after a session timeout be efficiently implemented in PHP?
When a user's session times out, they should be redirected to a logout page to ensure their account remains secure. This can be achieved by checking the session expiration time against the current time on each page load, and if the session has expired, redirect the user to the logout page.
// Check session expiration time
if(isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > 1800)) {
session_unset();
session_destroy();
header("Location: logout.php");
exit;
}
// Update last activity time
$_SESSION['last_activity'] = time();
Keywords
Related Questions
- How can PHP developers ensure that their code only produces natural number results when using math operators?
- How can the PHP include command cause unwanted div displacement on a webpage?
- What best practices should be followed when combining HTML forms with PHP scripts to handle user input for generating dynamic content?