Hi friends, in this tutorial I will show you how to create an automatic wait / exit session using PHP after 10 minute of inactivity. Currently the most important session concept for logged in users. If the user forgets to leave the page, the security risk increases and there is the possibility of data theft by the user. In this case I created a session variable and stored the current time in the variable. If a user is inactive at the last minute, they will automatically log out of the system and be redirected to the login page. In this tutorial I will explain how to delete a session after 10 minutes of user inactivity with PHP.
Table of Contents
Create Database and Table by SQL query
-- Database: `webscodex` -- -- -------------------------------------------------------- -- Table structure for table `admins` -- CREATE TABLE `admins` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `name` varchar(50) NOT NULL, `username` varchar(50) NOT NULL, `password` varchar(50) NOT NULL, `created` datetime NOT NULL DEFAULT current_timestamp() ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `admins` -- INSERT INTO `admins` (`id`, `name`, `username`, `password`, `created`) VALUES (1, 'manish', 'manish123', 'admin', '2021-01-30 20:24:31');
Create Database Configuration File.
<?php // Database configuration $hostname = "localhost"; $username = "root"; $password = ""; $dbname = "webscodex"; // Create database connection $con = new mysqli($hostname, $username, $password, $dbname); // Check connection if ($con->connect_error) { die("Connection failed: " . $con->connect_error); } ?>
Create Login HTML Page and PHP login Code
<?php // start session session_start(); // Include database connectivity include_once('config.php'); if (isset($_SESSION['NAME'])) { header("Location:dashboard.php"); exit(); } if (isset($_POST['submit'])) { $errorMsg = ""; $username = $con->real_escape_string($_POST['username']); $password = $con->real_escape_string($_POST['password']); if(!empty($username) && !empty($password)){ $query = "SELECT * FROM admins WHERE username = '$username' AND password ='$password'"; $result = $con->query($query); if($result->num_rows > 0) { $row = $result->fetch_assoc(); $_SESSION['NAME'] = $row['name']; $_SESSION['LAST_ACTIVE_TIME'] = time(); header("Location:dashboard.php"); die(); } else{ $errorMsg = "Username or Password is Invalid"; } }else{ $errorMsg = "Username and Password is required"; } } ?> <!DOCTYPE html> <html lang="en"> <head> <title>Automatic logout after 10 min of user Inactivity in page using PHP Mysql</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> </head> <body> <div class="card text-center" style="padding:20px;"> <h3>Automatic logout after 10 min of user Inactivity in page using PHP Mysql</h3> </div><br> <div class="container"> <div class="row justify-content-center"> <div class="col-md-4 col-md-offset-4"> <?php if (isset($errorMsg)) { ?> <div class="alert alert-danger alert-dismissible fade show"> <button type="button" class="close" data-dismiss="alert">×</button> <?php echo $errorMsg; ?> </div> <?php } ?> <div class="card"> <div class="card-body"> <img class="card-img-top" src="img_avatar1.png" style="width:25%;border-radius:50%;margin-left:110px;"> <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="POST"> <div class="form-group"> <label for="username">Username:</label> <input type="text" class="form-control" name="username" placeholder="Username"> </div> <div class="form-group"> <label for="password">Password:</label> <input type="password" class="form-control" name="password" placeholder="Password"> </div> <div class="form-group"> <input type="submit" name="submit" class="btn btn-primary btn-block" value="Login"> </div> </form> </div> </div> </div> </div> </div> </body> </html>
Preview:
Create Dashboard/Profile after login successful
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Automatic logout after 10 min of user Inactivity in page using PHP Mysql</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <div class="row" style="margin-top:70px;"> <?php include_once('check_user.php'); ?> <div class="col-md-12 card text-center" style="padding:50px;"> <h3>Welcome <span class="text-success"><?php echo ucwords($_SESSION['NAME']); ?> </span> to the Webs Codex</h3> <h3>Automatic Logout after 10 minute of user Inactivity in page</h3> <p><a href='logout.php'>Logout</a></p> </div> </div> </div> </body> </html> <!-- The Modal --> <div class="modal" id="myModal"> <div class="modal-dialog"> <div class="modal-content"> <!-- Modal Header --> <div class="modal-header"> <h4 class="modal-title">Session Expiration</h4> </div> <!-- Modal body --> <div class="modal-body"> Because you have been Inactivity, your session is about to expire. </div> <!-- Modal footer --> <div class="modal-footer"> <a href="index.php" class="btn btn-primary btn-sm">Login again</a> </div> </div> </div> </div> <script type="text/javascript"> setInterval(check_user, 2000); function check_user(){ $.ajax({ url:'check_user.php', method:'POST', data:'type=logout', success:function(result){ if (result == "logout") { $("#myModal").modal({ backdrop: 'static', keyboard: false, }); setTimeout(function(){ $('#myModal').modal('hide') window.location.href="logout.php"; }, 10000); } } }); } </script>
Before Session Active
Preview:
After Session Expire
Preview:
Create check_user.php File for Check time
<?php session_start(); if (isset($_POST['type']) && $_POST['type'] == 'logout') { if ((time() - $_SESSION['LAST_ACTIVE_TIME']) > 600) { // 60*10 Time in Seconds echo "logout"; } }else{ if (isset($_SESSION['LAST_ACTIVE_TIME'])) { if ((time() - $_SESSION['LAST_ACTIVE_TIME']) > 600) { // 60*10 Time in Seconds header("Location:logout.php"); die(); } } $_SESSION['LAST_ACTIVE_TIME'] = time(); if (!isset($_SESSION['NAME'])) { header("Location:index.php"); die(); } } ?>
Create Users Logout File
<?php session_start(); session_destroy(); session_unset($_SESSION['NAME']); session_unset($_SESSION['LAST_ACTIVE_TIME']); header("Location:index.php"); die(); ?>
You can always support by sharing on social media or recommending my blog to your friends and colleagues.If you have any suggestions / problems about this tutorial, please comment on the form below.😊
Greate article. Keep writing such kind of info on your blog.
Im really impressed by your blog.
Hi there, You’ve performed an excellent job. I will certainly
digg it and in my opinion recommend to my friends.
I’m sure they’ll be benefited from this
web site.