Auto logout system in PHP
Hi, everyone. How are you? All are welcome in my new tutorial. Please read this tutorial and try with example code.
All of developers must use the auto logout system in php. Mainly in admin panel area where other user is not applicable for use. So we are discussing about how to make a auto logout system in php. It’s very simple to make and I am using SESSION variable to making this system. So lets start.
See video tutorial of this post just below of this page
First look at my login page(index.php) and action page(login.php) : –
index.php
<?php require_once 'db.php'; if(!empty($_SESSION['admin_id'])){ header('location:dashboard.php'); } ?> <!DOCTYPE html> <html> <head> <title>Login Page</title> </head> <body> <center> <form action="login.php" method="post"> Email : <input type="email" name="email"><br> password : <input type="password" name="password"><br> <input type="submit" name="submit" value="Login"> </form> </center> </body> </html>
login.php
<?php require_once 'db.php'; if(isset($_REQUEST['submit'])){ $email = $_REQUEST['email']; $password = $_REQUEST['password']; $qry = mysqli_query($con,"SELECT * from `admin` WHERE email = '".$email."' AND password = '".$password."'"); $row = mysqli_num_rows($qry); if($row>0){ $data = mysqli_fetch_assoc($qry); $_SESSION['admin_id'] = $data['id']; $_SESSION['auto_logout_time'] = time(); header('location:dashboard.php'); } else{ header('location:index.php'); } } ?>
See in the login.php page, I have used two session variable named $_SESSION[‘admin_id’] and $_SESSION[‘auto_logout_time’]
Here the $_SESSION[‘auto_logout_time’] is the key to make this.
Now look at my dashboard.php page after admin logged in
dashboard.php
<?php require_once 'db.php'; if(empty($_SESSION['admin_id'])){ header('location:index.php'); } if((time() - $_SESSION['auto_logout_time'])>300){ header('location:logout.php'); } ?> <h1>Welcome Admin</h1> <a href="logout.php">Click here for logout</a>
Here in dashboard page you see I have make a condition and checking if the (current time-session variable time)is greater than 300 or 5 minutes it will redirect in logout.php page
Now look at my logout.php page :-
logout.php
<?php session_start(); unset($_SESSION['admin_id']);; session_destroy(); echo "<script>window.location.href='index.php'</script>"; ?>
Hello there! Would you mind if I share your blog with my facebook
group? There’s a lot of people that I think would really enjoy your content.
Please let me know. Thanks
Sure