0

In my application I need to make sure that if a user moves away from the application (by closing the tab, closing the browser, or navigation to another page) that if they try to come back to the application (using the back button, history, or typing the link) they are directed to a screen that makes them log back in.

I think I have this all worked out:

  1. On every page, check to see if my session is available.
  2. If it is, move on. If not, redirect to "You must log in again." page.
  3. On the window.onbeforeunload() event, run a destroy.php script.
  4. The destroy script kills the session.

But I can NOT get my destroy script loaded from the onbeforeunload() event.

Here is the index file, that starts things off:

<?php

/***********************
INDEX for CloseTab test
************************/

// Start the session
echo "<pre>";
echo "Starting session now...";
session_start();

// Put something in the variable that we can get on another page
$_SESSION["name"] = "Joe";
echo "\nJust set session var 'name' to 'Joe'.";

?>

<!-- Open that other page -->
<a href= <?php echo "home.php"; ?> > Click here to open Home page</a>

Here is the HOME page, just to have somewhere to go and test for the session:

    <head>

        <!-- ***********************
        HOME for CloseTab test
        ************************** -->

        <!-- Link to jQuery file  -->
        <script   src="https://code.jquery.com/jquery-3.1.1.min.js"   
              integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="   
              crossorigin="anonymous"></script>

        <!-- Link to our custom js code.. -->
        <script type="text/javascript" src=<?php echo "my_scripts.js></script> 

    </head>

    <?php

    // Start the session
    session_start();

    // See if there is any indication that a session is not available.
    // Test with closing tab, closing browser, navigating away from page.
    // We want to see this message if the user is coming here from anywhere except the index page.
    // Test back button, typing the URL, browser history.
    if ( (!isset($_SESSION)) || (session_status() == PHP_SESSION_NONE) || (count($_SESSION) < 1) ) {
        echo "<pre>";
        echo "Your session is not longer active.  Log in again.";
        echo "\n\nPretending to go to a login page...";
        exit;
    }

    ?>

    <!-- If the session is good, we MUST have come from index page, and can access the session var. -->
    <div class="container">
        <h1>Home Page</h1>
        <h2>Here is the name from the session var: <?php echo $_SESSION["name"]; ?> </h2>
    </div>

<div>
    <h3><a href= <?php echo "destroy.php"; ?> > Click here to log out</a></h3>
</div>

</html> 

Here is my javascript code:

/***********************
my_scripts.js
************************/

console.log("in js file");

// Before a page unloads, run the destroy code
window.onbeforeunload = function() {
    console.log("inside onbeforeunload");             // I get this to print

    // Try to execute with AJAX call                  // Nothing in the middle seems to be running
    $.ajax({
        type: "GET",
        url: "destroy.php",
        async: false                     
     });

    // Try with jQuery syntax
    $("container").load("destroy.php");

   console.log("Got this far");                       // I get this to print
}

Here is the destroy code I am trying to load:

<?php

/******************************************************************
Destroy
- Clears the session var and destroys the session if user leaves app.
******************************************************************/

// Unset all of the session variables and destroy the session.
session_start();
$_SESSION = array();
session_destroy();

?>

<script type="text/javascript">
    // Place message in the console that we can see even if the window closes.
    console.log("DONE!  Session destroyed.")
</script>
B. Krafft
  • 147
  • 1
  • 13
  • 1
    Possible duplicate of [JavaScript, browsers, window close - send an AJAX request or run a script on window closing](http://stackoverflow.com/questions/6162188/javascript-browsers-window-close-send-an-ajax-request-or-run-a-script-on-win) – hindmost Mar 30 '17 at 15:02

1 Answers1

1

You need to be careful with onbeforeunload. Browsers don't let you do too much in this event.

If you want to make an AJAX call, you need to add async: false. That's something that's usually discouraged, but here, if the call is asynchronous, then the browser will probably finish the event and close the page before the call is done.

$.ajax({
    type: "GET",
    url: "destroy.php",
    async: false
 });
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • Thank you so much for thinking about this. But that still doesn't work. When I navigate away and then hit the "back" button, the session is still there and I never get the "DONE Session destroyed" message. So it's still not firing. – B. Krafft Mar 31 '17 at 17:30