Automatic Logout after 10 minutes of inactive Session in PHP
In this tutorial, we will how to apply automatic logout after 10 minutes of inactive session.
Step 1: Start a new session by using session_start()
the function at the beginning of the script.
Step 2: Set a timer when the user logs in or accesses a page by setting a session variable with the current time, for $_SESSION[‘last_activity’] = time();
Step 3: On every page load, the system checks the difference between the current time and the last activity time. If the difference is greater than 10 Minutes(10*60 seconds), the user session will logout and redirect to the login page.
1 2 3 4 5 6 7 8 9 |
<?php session_start(); // Check if last activity was set if (isset($_SESSION['last_activity']) && time() - $_SESSION['last_activity'] > 600) { session_unset(); // unset $_SESSION variable session_destroy(); // destroy session data in storage header("Location: login.php"); // redirect to login page } $_SESSION['last_activity'] = time(); // update last activity time stamp ?> |
Place the above code on the page where you want to implement the auto-logout feature.