How To Create User Login Logout Session Timeout Using PHP

Good Day!!!

In this article, we are going to learn on How To Create User Login Logout Session Timeout Using PHP. This user login is a very common tutorial for us. In this case, we are going to add a function. In the user login, we set a session expiration time when the user logged-in. If the account of user elapsed to the set time then the user will no longer access his/her account and it will automatically log out after refreshing the page. HTML Source Code This HTML source code is to show the login form for the user.
  1. <form method="post" action="">
  2. <?php if($message!="") { ?>
  3. <div id="message" class="blink_text"><?php echo $message; ?></div>
  4. <?php } ?>
  5. <table border="0" cellpadding="10" cellspacing="1" class="tblLogin">
  6. <tr class="tableheader">
  7. <td align="center" colspan="2">Login Details</td>
  8. </tr>
  9. <tr class="tablerow">
  10. <td align="right">Username</td>
  11. <td><input type="text" autofocus="autofocus" class="textbox_detail" name="user_name"></td>
  12. </tr>
  13. <tr class="tablerow">
  14. <td align="right">Password</td>
  15. <td><input type="password" autofocus="autofocus" class="textbox_detail" name="password"></td>
  16. </tr>
  17. <tr class="tableheader">
  18. <td align="center" colspan="2"><input type="submit" class="btn_submit" name="submit" value="Login"></td>
  19. </tr>
  20. </form>
PHP Script This PHP script is used to check the session account of the user if the login session expiration time is reached.
  1. <?php
  2. include("functions.php");
  3. $message="";
  4. if(count($_POST)>0) {
  5.         if( $_POST["user_name"] == "admin" and $_POST["password"] == "admin") {
  6.                 $_SESSION["user_id"] = 1001;
  7.                 $_SESSION["user_name"] = $_POST["user_name"];
  8.                 $_SESSION['loggedin_time'] = time();  
  9.         } else {
  10.                 $message = "Invalid Username or Password!";
  11.         }
  12. }
  13.  
  14. if(isset($_SESSION["user_id"])) {
  15.         if(!isLoginSessionExpired()) {
  16.                 header("Location:home.php");
  17.         } else {
  18.                 header("Location:logout.php?session_expired=1");
  19.         }
  20. }
  21.  
  22. if(isset($_GET["session_expired"])) {
  23.         $message = "Session is Expired. Please Login Again.";
  24. }
  25. ?>
Our tutorial look like this: This is the login form. Login Form This is our Home Page. Home Page If the user session is a timeout. Time Out So what can you say about this work? Share your thoughts in the comment section below or email me at [email protected]. Practice Coding. Thank you very much.

Add new comment