Waelhi
Waelhi

Reputation: 315

call php function when browser back button clicked

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?

Upvotes: 0

Views: 4619

Answers (2)

Ares Draguna
Ares Draguna

Reputation: 1661

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.

Upvotes: 1

James McClelland
James McClelland

Reputation: 555

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");
}

Upvotes: 1

Related Questions