How can server-side PHP be used to automatically log out a user after a certain period of inactivity?
To automatically log out a user after a certain period of inactivity using server-side PHP, you can store a timestamp of the user's last activity in a session variable. Then, on every page load, you can check if the current time minus the last activity timestamp exceeds the desired inactivity period. If it does, you can destroy the session and log the user out.
session_start();
$inactive_time = 1800; // 30 minutes in seconds
if(isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > $inactive_time)) {
session_unset();
session_destroy();
// Redirect to login page or any other desired action
}
$_SESSION['last_activity'] = time();
Related Questions
- What are the best practices for validating form data on the server side in PHP, especially when using JavaScript for client-side validation?
- How can inline styles be avoided when implementing automatic code color coding in PHP?
- Are there any potential issues or limitations when using print_r with the second parameter set to true in PHP versions prior to 4.3.0?