Destroy PHP session on page leaving

前端 未结 7 1127
轻奢々
轻奢々 2020-12-06 02:52

I need to destroy a session when user leave from a particular page. I use session_destroy() on the end of the page but its not feasible for me because my page h

相关标签:
7条回答
  • 2020-12-06 03:20

    Doing something when the user navigates away from a page is the wrong approach because you don't know if the user will navigate to a whole different page (say contact.php for the sake of the argument) or he/she will just go to the next page of abc.php and, as Borealid pointed out, you can't do it without JS. Instead, you could simply add a check and see if the user comes from abc.php:

    First, in your abc.php file set a unique variable in the $_SESSION array which will act as a mark that the user has been on this page:

    $_SESSION['previous'] = basename($_SERVER['PHP_SELF']);
    

    Then, add this on all pages, before any output to check if the user is coming from abc.php:

    if (isset($_SESSION['previous'])) {
       if (basename($_SERVER['PHP_SELF']) != $_SESSION['previous']) {
            session_destroy();
            ### or alternatively, you can use this for specific variables:
            ### unset($_SESSION['varname']);
       }
    }
    

    This way you will destroy the session (or specific variables) only if the user is coming from abc.php and the current page is a different one.

    I hope I was able to clearly explain this.

    0 讨论(0)
提交回复
热议问题