Home » Interview Questions, PHP/MySQL, Programming Techniques » PHP – Expire Session When Page is Refreshed or Browser Back Button is Clicked

0

I would not say this is a great feature to have in a web application. But many people wanted to learn how the user session of a web application can be ended if the logged in user clicks on the Back button in the browser or refreshes the page. You might have seen this feature implemented in many online banking applications and online ticket booking sites. Actually, this is a bad user experience as an accidental pressing of Backspace button or clicking of Back button will require the user to log in to the application again. But this is considered as a extended security feature this will prevent XSRF to a great extent. But this is a performance killer, so make sure you have enough bandwidth and infrastructure in place to handle the situation.

I am now going to talk about how we can implement this behavior in a PHP application. There are two things that we need to do to achieve this behavior.

  1. Make sure the webpage is not cached in browsers and that the browser makes a request to the server every time a page is opened in the browser, even if the user navigates to a page by clicking the Back button. This way, browser will not render anything from the cache but will make a request to the server to fetch fresh content every time.
  2. Define and validate a unique token for each request. You will have to generate a unique token for each request and all expect the next request from the user to have this token defined in the URL.

I have created a sample prototype to demo this feature. This is just a one page web app with no proper authentication done. This is just a prototype for you to understand how the behavior is implemented. You can scale it and use it according to your needs and to fit in your applications.

<?PHP
session_start();
$action = $_GET['action'];
if($action == 'login') {
    // Authenticate the user somehow - now it just logs the user in without any credentials
    // Generate a request token that will be valid only for one request
    // Next request from the user should have this token set in the url
    $_SESSION['user'] = 'TestUser';
    $token = md5(microtime() . 'TestUser' . 'secret') . uniqid('', true);
    $_SESSION['token'] = $token;
    header('Location: refresh.php?action=home&token=' . $token);
    exit;
} else {
    if(!isset($_SESSION['user']) || $_GET['token'] != $_SESSION['token']) {
        unset($_SESSION['user']);
        unset($_SESSION['token']);
        echo 'Your Session has Expired! Please login again: <a href="refresh.php?action=login">Login</a>';
        exit;
    }
    $token = md5(microtime() . 'TestUser' . 'secret') . uniqid('', true);
    $_SESSION['token'] = $token;
}
// These headers tell the browser to not load anything from cache at all
// and force the browser to make a server request even on a Back click
// Allowing us to verify the token
header('Expires: 0');
header('Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Pragma: no-cache');
?>
Current User: <?php echo $_SESSION['user']; ?><br/>
Request Processed at: <?php echo time(); ?><br/>
<a href="refresh.php?action=home&token=<?php echo $token; ?>">Click to Navigate</a>

You just need to make sure that the $token parameter is added to all URLs in your page.

Save the code in a PHP file and run it using a browser and it will ask you to login. The dummy login function will log you in and it will start generating tokens for each request and validate it. As long as you keep on clicking on the Navigate link, the session will be active. The moment you use the browser Back button to navigate or refresh the page, the session will be expired and will ask you to login again.

Please let me know if you have any questions.

Leave a Reply

Page optimized by WP Minify WordPress Plugin