How can a PHP session with a time limit be implemented to automatically log out a user after a specified period?
To implement a PHP session with a time limit to automatically log out a user after a specified period, you can set a session timeout value and check if the user's last activity time exceeds this limit on each page load. If the limit is exceeded, you can destroy the session and redirect the user to the login page.
// Set session timeout value to 30 minutes
$session_timeout = 1800; // 30 minutes in seconds
// Start the 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 the user to the login page
header("Location: login.php");
exit();
}
// Update last activity time
$_SESSION['last_activity'] = time();
Related questions
-
PHP MySQL SHOW TABLES
-
XML encoding decoding
-
PHP server IP addresses file uploads