0

How can I call a PHP Function when Browser Back button clicked or right click then clicked BACK item then prevent page to redirect to login page when user is still logged-in.

I found this (Pressing back button redirects the logged user to log out?) to prevent page to redirect to other page when user clicked browser back button and user is still logged in, but I didn't know where to put those codes and how to call that function.

Can someone explain this thoroughly to accomplish my problem or provide some DEMO(JSFiddle) for better understanding?

Community
  • 1
  • 1
Waelhi
  • 315
  • 2
  • 7
  • 19

2 Answers2

1

You could use a header redirect on the login page to check if the user is logged in, but this will have to be called before any page data is sent:

if(isset($_SESSION['username'])){
    header("Location: home.php");
}
James McClelland
  • 555
  • 4
  • 16
  • I imagine he's handling the login on the index page which is why he sees the 'page expired' message when he hits back. but using a separate login page and a redirect is a better approach +1 – andrew Oct 22 '14 at 10:31
1

You can try to use this:

jQuery(document).ready(function($) {

  if (window.history && window.history.pushState) {

    window.history.pushState('forward', null, './#forward');

    $(window).on('popstate', function() {
      alert('Back button was pressed.'); //here you know that the back button is pressed
    });

  }
});

You can find the answer Here

What this does, it checks with JS if the back button was pushed and if so, you can perform whatever action you want. If a redirect is what you need, use window.location = "http://www.yoururl.com"; OR window.navigate("http://www.yoururl.com"); //works only with IE

Alternatively, you can place an jquery ajax call there, that sends posted requests back to a certain page, and you can check them like:

if(isset($_POST['ajax_response_from_js_script'])  {
    //call PHP function
}

Hope it helps!
Keep on coding!
Ares.

Community
  • 1
  • 1
Ares Draguna
  • 1,641
  • 2
  • 16
  • 32