PHP auto logout when browser or tab is closed

It is often mistaken between session destroy and logout in php. It is very easy to log an user out if he/she clicks on logout button. It simply performs a session destroy action and redirect the user to logout page. But what if user click on browser close button ? Can you fire an event to logout the person logged in ? This would create issue if you have integrated a custom online/offline system in your web application. The user who has closed the tab would appear as online to other members. Here is a simple procedure to automatically logout a user if browser or tab is closed. PHP auto logout when browser or tab is closed:

PHP auto logout when browser or tab is closed
PHP auto logout when browser or tab is closed

Initiate two separate javascript to check and update current time stamp and time laps respectively. The following javascript update the current timestamp in timestamp column in database.

The javascript below just check the time laps between last time stamp and current time stamp

Now suppose a user is logged in say user 45, both js will perform action after every 10 second. The timestamp column will be updated and checked periodically. Since the time interval is of 10 second for both js the time gap for check.js will always be less than 60 seconds as update.js periodically update after 10 second. 

Now suppose the browser is closed by  user 45 without clicking logout button. All other members who are logged in would be seeing him online for 1 minute. All other members who are logged in would be running the same js script at their side. Now check.js of another user say user 46 will check the entire timestamp column and it would find that the current time stamp is greater than last time stamp of user 45 as he has closed the tab already and stopping update.js. So check .js of user 46 will simply update the database status of user 45 as offline.

How to Add Magnifying Zoom for Images in WordPress

How to Create a Product Catalog in WordPress (without a Shopping Cart)


  1. Marcelo Oliveira

    Hi Kishor,

    I liked your idea, but I have one doubt.

    How can I pass the userid from PHP to JS ? And where would be the best place to do that ?


    1. Kishor Parida Author

      if you are writing js in php file itself then pass the variable in js like
      var x = “< ?php echo $userid; ?>“;
      or else
      store the userid in a hidden field lest say ” id=”user_id” />
      get the value using


Comments are closed.