phpsessionsession-variablessession-cookiessession-timeout

Destroy PHP Sessions on Browsers Tab Close


i am stucked, i am working on Projects hotbartendersla

i have used a lot of sessions to process data in event booking, now i want to destroy the session when user closed the window/tab of browser,because when ever i open site the selection remains same as i did.

i have used this

<script type="text/javascript">
  window.onbeforeunload = function() {

    $.post("mysessionsdestroypage.php",function(data){
    });  

  }
</script>

but when i jumped to on step 2,step 3, my sessions are destroyed and data don't reached on step 4. i searched alot but i found no reliable solution for this


Solution

  • First of all Set Session time out on the page where you want to clear Sessions

    <?php
    // destroy session in 15 minutes, 900 ms =15 minutes
    
    if (isset($_SESSION['LAST_ACTIVITY_step1']) && (time() -   $_SESSION['LAST_ACTIVITY_step1'] > 900)) {
    
     header("Location:http://www.hotbartendersla.com/session-destroy");
     }
     $_SESSION['LAST_ACTIVITY_step1'] = time(); // the start of the session.
    
    ?>
    

    Then make a new page(in wordpress) to destroy sessions and add template to that page,

    pagedestroy-sessions.php
    
    <?php
    /*
    Template Name: Destroy Sessions
    */
    session_start();
    
    include('header.php');
    
    
     session_destroy();
     session_unset();
     ?>
     <h2>Session Has Been Destroyed </h2>
    <?php
    include('footer.php');
    ?>
    
    <script type="text/javascript">
    function redirect() {
      document.location = 'https://www.hotbartendersla.com/event-booking-step-1';
    }
      <!- after 1 second redirect to event-booking-step-1 Page-->
      setTimeout(redirect(),1000);
    
    </script>