In this tutorial, I’m going to show you how to set up expiration on PHP sessions. This tutorial will not give you a good design but will provide you with an idea in setting up session and expiry in PHP.
Creating a Login Form and Login Script
First, we create our login form with the login script. We have set up the session and expiry on the login script upon user submission if username and password are correct. We name this as “index.php”.
<!DOCTYPE html> <html> <head> <title>How to Set Up Expiration to Sessions using PHP</title> </head> <body> My username: neovic <br> My password: devierte <h2>Login Form</h2> <form method="POST"> Username: <input type="text" name="username" required> Password: <input type="password" name="password" required> <input type="submit" value="Login" name="login"> </form> <br> <?php if (isset($_POST['login'])){ session_start(); $username=$_POST['username']; $password=$_POST['password']; if ($username=="neovic" and $password=="devierte"){ $_SESSION['user']=$_POST['username']; $_SESSION['expiry']=time() + (5*60); //set up session to expire within 5 min header('location:goto.php'); } else{ echo "Username or Password did not match!"; } } ?> </body> </html>
Creating a Goto Page
Next step is to create our goto page if the login input matches. We have included in this page a Logout link that will destroy our session. We name this as “goto.php”.
<?php session_start(); $now = time(); if (!isset($_SESSION['user'])) { echo "Session not Set. Login"."<br>"; ?> <a href="index.php">Login Here</a> <?php } elseif ($now > $_SESSION['expiry']) { session_destroy(); echo "Your session has expired! Login again"."<br>"; ?> <a href="index.php">Login Here</a> <?php } else{ ?> <!DOCTYPE html> <html> <head> <title>How to Set Up Expiration to Sessions using PHP</title> </head> <body> <h2>Welcome - <?php echo $_SESSION['user']; ?></h2> <a href="logout.php">Logout</a> </body> </html> <?php } ?>
Creating a Logout Script
Lastly, we create our logout script. This script will destroy our current session and will redirect us back to our login page. We name this script as “logout.php”.
<?php session_start(); session_destroy(); header('location: index.php'); ?>
Happy Coding!
Download Code