Introduction

In this post we will see how to show warning message to user when session expires in a web application. So we will redirect user to login page once session has expired.

We know that we let users login to the web application before a user can perform some sensitive activities like online transactions, updating user’s profile etc. So we need to maintain session for these kind of activities and a session is built for a specific time period.

A session is attached to a client or user. Therefore when time period is over for a particular session then the session gets expired and user no longer is able to continue his/her activities. In such case a user has to re-login to continue the activities.

Generally a session expires when a user is idle for session time period or a session expires irrespective of whether a user is idle or not. Therefore in such situation a meaningful message would let user know that his/her session has been expired otherwise user may be confuse what happened suddenly.

Here we will build example using PHP but you can use any framework to use the concept for showing warning message to the users.

This example gives an overlay message which will be retained for 5 seconds before redirecting to the login page.

Prerequisites

Knowledge of PHP, HTML, CSS, JavaScript

Apache 2.4 HTTP Server, PHP 7.3.5

Example

This example gives an overlay message which will be retained for 5 seconds before redirecting to the login page.

Creating Project Directory

We need to first create our root project directory in order to implement the Codeigniter multi-language website.

It’s assumed that you have setup Apache 2.4, PHP 7.3.5 in Windows system.

Next we will create a project root directory called php-session-expiry-message under the Apache server’s htdocs folder.

We may not mention the project root directory in subsequent sections and we will assume that we are talking with respect to the project root directory.

Creating Login Page

We will create a login page with login form, where user will input his/her credentials to login to the application.

Ideally credentials should be verified against database value or any persistent storage with strong encryption mechanism.

We keep the session alive for only 5 seconds in our example but ideally your session should be kept alive more than 5 seconds but not for too long time period.

<?php

$errors = '';
$clss = 'error';

if (isset($_POST['login'])) {
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);

    if (empty($username) || empty($password)) {
        $errors .= "\nUsername and Password required.";
    } else {
        if($username === 'roy' && $password === 'roy') {
			session_start();
			$_SESSION['start_time'] = time();
			$_SESSION['expiry_time'] = $_SESSION['start_time'] + 5; //expiry in 5 sec
			$_SESSION['user_name'] = $username;
			header('Location: /php-session-expiry-message/home.php');
			exit;
		} else {
			$errors .= "\nInvalid Username and Password";
		}
    }
}
?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>PHP Login</title>
        <style type="text/css">
            .error {
                color: red;
            }
            .success {
                color: green;
            }
        </style>
    </head>
    <body>
        <form method="post" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>">
			<?php
				if (!empty($errors)) {
					echo "<p class='" . $clss . "'>" . nl2br($errors) . "</p>";
				}
			?>
            <h3>Login</h3>
            <div>
                <input type="text" name="username" title="Username"
                       tabindex="1" autocomplete="off"
                       value="<?php echo @htmlspecialchars($_POST['username']); ?>"/>
            </div>
            <div>
                <input type="password" name="password" title="Password" tabindex="2" autocomplete="off"/>
            </div>
            <div>
                <input type="submit" name="login" value="Login" tabindex="4"/>
            </div>
        </form>
    </body>
</html>

Creating Logout Page

This is the page which is triggered when user wants to logout from the application or application auto-logouts the user from the application.

<?php

function user_logout() {
    session_start();
    $_SESSION = array(); // reset session array
    session_destroy();   // destroy session.
    header('Location: /php-session-expiry-message/login.php');
    exit;
}

user_logout();

/*
 * End of file logout.php
 */

Creating Home Page

This the page which is shown upon the successful login of the user.

We show an warning message to user when session expires to the user when session expires and this message is being shown for 5 seconds before it redirects to the login page automatically.

During this 5 seconds period user may click on the login link to go to the login page manually.

<?php
    session_start();
?>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>My Home</title>
		
		<script type="text/javascript">
			function overlay() {
				el = document.getElementById("overlay");
				el.style.visibility = (el.style.visibility == "visible") ? "hidden"
						: "visible";
				setTimeout(function() {
					window.location = "/php-session-expiry-message/login.php";
				}, 5000);
			}
			var secondsBeforeExpire = <?php echo ($_SESSION['expiry_time'] - $_SESSION['start_time']);?>; //5 sec expiry time
			setTimeout(function() {
				overlay();
			}, secondsBeforeExpire * 1000);
		</script>
		
		<style type="text/css">
			#overlay {
				visibility: hidden;
				position: absolute;
				left: 0px;
				top: 0px;
				width: 100%;
				height: 100%;
				text-align: center;
				z-index: 1000;
			}

			#overlay div {
				width: 300px;
				height: 100px;
				margin: 100px auto;
				background-color: #fff;
				border: 2px solid #000;
				padding: 15px;
				text-align: center;
				font-size: 16px;
				font-weight: bold;
			}
		</style>
	</head>
	<body>
<?php	
	if(!isset($_SESSION['user_name'])) {
		header('Location: /php-session-expiry-message/login.php');
		exit;
	} else {
        $now = time(); // Checking the time now when home page starts.
        if ($now > $_SESSION['expiry_time']) {
			$_SESSION = array();
            session_destroy();
            echo "Your session has expired! <a href='/php-session-expiry-message/login.php'>Login here</a>";
        } else {
?>
		Welcome <?php echo $_SESSION['user_name']; ?>. You have successfully logged in.
		<a href="/php-session-expiry-message/logout.php" onclick="return confirm('Are you sure want to logout?')">Logout</a>
<?php
		}
	}
?>
		<div id="overlay">
			<p>
				Your session has expired!<br /><br />Please <a href="login.php">Click Here</a>
				to go back to Login Page. <br />
				<br />
				<br /> You will be automatically redirected after 5 seconds...
			</p>
		</div>
	</body>
</html>

Testing the Application

Login Page

warning message on session expiry

Home Page

Login using username – roy and password – roy, you will see below home page.

warning message to user when session expires

When session expires you will see below warning message in the page:

warning message on session expiry

After 5 seconds you will be redirected to the login page.

Source Code

You can download source code.

That’s all. Thanks for reading.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *