What are the best practices for automatically redirecting a user to a logout page after a certain time limit in PHP sessions?
To automatically redirect a user to a logout page after a certain time limit in PHP sessions, you can set a session variable with the last activity time and check it on each page load. If the time limit has been exceeded, you can destroy the session and redirect the user to the logout page.
<?php
// Start the session
session_start();
// Set the time limit in seconds (e.g. 30 minutes)
$inactive = 1800;
// Check if session variable last_activity is set
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > $inactive)) {
// Destroy the session
session_unset();
session_destroy();
// Redirect to the logout page
header("Location: logout.php");
exit();
}
// Update last activity time
$_SESSION['last_activity'] = time();
// Your regular PHP code goes here
?>
Related Questions
- What is the significance of the error message "mysql_fetch_array() expects parameter 1 to be resource, boolean given" in PHP?
- How can PHP developers avoid errors related to invalid date calculations when using functions like mktime?
- What are best practices for handling exceptions in PHP when executing SQL commands?