Are there best practices for implementing an auto-logout feature in a PHP login script?
To implement an auto-logout feature in a PHP login script, you can set a session timeout period and check if the user's last activity was within that time frame. If not, you can destroy the session and log the user out automatically.
// Set session timeout period (e.g. 30 minutes)
$timeout = 1800; // 30 minutes in seconds
// Check if user's last activity was within the timeout period
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity']) > $timeout) {
// Destroy the session and log the user out
session_unset();
session_destroy();
// Redirect to the login page
header("Location: login.php");
exit;
}
// Update last activity timestamp
$_SESSION['last_activity'] = time();
Related Questions
- When including a script in PHP, what considerations should be made regarding variable scope visibility?
- What are the potential drawbacks of using procedural if/else/elseif or switch/case statements in PHP for handling user input and content display compared to OOP?
- What are some common pitfalls to avoid when using MySQL queries in PHP for sorting and displaying data?