Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent back button after logout

I don't want the user to go back to secured pages by clicking back button after logging out. In my logout code, I am unsetting the sessions and redirecting to login page.But, I think the browser is caching the page so it becomes visible despite the session being destroyed from logout.

I am able to avoid this by not allowing the browser to cache

header("Cache-Control", "no-cache, no-store, must-revalidate")

But this way I am loosing the advantage of Browser Caching.

Please suggest a better way of achieving this. I feel, there must be a way of handling this by javascript client side

like image 759
piyush Avatar asked May 09 '12 07:05

piyush


People also ask

How do I keep the back button off when I log out flask?

Use the Cache-Control header to prevent a page from being cached. Show activity on this post. Then, if the user presses the back button, it will land on the page where the redirect is located and will get redirected again.


2 Answers

Implement this in PHP and not javascript.

At the top of each page, check to see if the user is logged in. If not, they should be redirected to a login page:

<?php 
      if(!isset($_SESSION['logged_in'])) : 
      header("Location: login.php");  
?>

As you mentioned, on logout, simply unset the logged_in session variable, and destroy the session:

<?php
      unset($_SESSION['logged_in']);  
      session_destroy();  
?>

If the user clicks back now, no logged_in session variable will be available, and the page will not load.

like image 124
Jonathan Spiller Avatar answered Oct 08 '22 04:10

Jonathan Spiller


I was facing this same problem and spent whole day in figuring out it, Finally rectified it as follows:

In login validation script if user is authenticated set one session value for instance as follows:

$_SESSION['status']="Active";

And then in User Profile script put following code snippet:

<?php

session_start();

if($_SESSION['status']!="Active")
{
    header("location:login.php");
}

?>

What above code does is, only and only if $_SESSION['status'] is set to "Active" then only it will go to user profile , and this session key will be set to "Active" only if user is authenticated... [Mind the negation [' ! '] in above code snippet]

Probably logout code should be as follows:

{
    session_start();
    session_destroy();
    $_SESSION = array();
    header("location:login.php");
}

Hope this helps...!!!

like image 22
Tushar Kshirsagar Avatar answered Oct 08 '22 03:10

Tushar Kshirsagar