How can PHP developers implement a timeout feature to automatically log out inactive users in a forum setting?
To automatically log out inactive users in a forum setting, PHP developers can implement a timeout feature by tracking user activity timestamps and comparing them against a predefined timeout period. If a user has been inactive for longer than the timeout period, they can be automatically logged out to enhance security and free up resources.
// Start session
session_start();
// Define timeout period (e.g. 30 minutes)
$timeout = 1800; // 30 minutes in seconds
// Check if user is logged in and there is a last activity timestamp
if(isset($_SESSION['user_id']) && isset($_SESSION['last_activity'])) {
// Calculate time difference between current time and last activity
$inactive_time = time() - $_SESSION['last_activity'];
// If inactive time exceeds timeout period, log user out
if($inactive_time > $timeout) {
session_unset();
session_destroy();
header("Location: logout.php");
exit();
}
}
// Update last activity timestamp
$_SESSION['last_activity'] = time();
Related Questions
- Is it possible to dynamically generate links in PHP based on the current directory using super global variables like $_SERVER?
- Is it recommended to store arrays in separate files or use databases for better organization and efficiency in PHP?
- What are potential pitfalls when passing variables from JavaScript to PHP in a web development project?