How can a user be automatically logged out after a certain period of inactivity in a PHP application?
To automatically log out a user after a certain period of inactivity in a PHP application, you can set a session timeout value and check the last activity time of the user on each page load. If the user has been inactive for longer than the session timeout value, you can destroy the session and redirect them to the login page.
// Set session timeout value in seconds
$session_timeout = 1800; // 30 minutes
// Start or resume session
session_start();
// Check if last activity time is set
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity']) > $session_timeout) {
// Destroy the session
session_unset();
session_destroy();
// Redirect user to login page
header("Location: login.php");
exit;
}
// Update last activity time
$_SESSION['last_activity'] = time();
Related Questions
- What are some recommended data structures for storing relationships in a family tree using PHP?
- In the context of generating Sudoku puzzles in PHP, what considerations should be made when determining the number of random numbers to remove from each array representing a puzzle grid?
- What are the best practices for inserting data into a MySQL database using PHP, especially in terms of handling variable values like temperature readings?