How can PHP developers ensure that users are automatically logged out after a certain period of inactivity?
To ensure that users are automatically logged out after a certain period of inactivity, PHP developers can implement a session timeout feature. This feature involves setting a session timeout value, checking the user's last activity time against the timeout value on each page load, and logging the user out if the timeout has been exceeded.
// Set session timeout value (e.g. 30 minutes)
$session_timeout = 1800; // 30 minutes in seconds
// Check if user is logged in and there is a last activity time stored in session
if(isset($_SESSION['loggedin']) && isset($_SESSION['last_activity'])){
// Calculate time since last activity
$inactive_time = time() - $_SESSION['last_activity'];
// If inactive time exceeds session timeout, log user out
if($inactive_time > $session_timeout){
// Unset all session variables and destroy session
$_SESSION = array();
session_destroy();
// Redirect user to login page
header("Location: login.php");
exit;
}
}
// Update last activity time on each page load
$_SESSION['last_activity'] = time();
Related Questions
- What are some strategies for troubleshooting and debugging PHP code that involves switch statements and include functions for website functionality?
- How can PHP extract information from the user agent to determine browser version or screen resolution?
- What is the best practice for storing file extensions in an array for use in an upload script in PHP?