0

I am working on PHP and MySql. I need a feature, when user close browser tab, a user should log out automatically. I have used javascript onbeforeunload event. But it is not working, this event executes for page refresh also.

Here is my sample code,

window.onbeforeunload = function(){
    $.ajax({url: "logout.php", success: true});
    return 'Are you sure ?';
};
Rahul
  • 223
  • 1
  • 2
  • 10

1 Answers1

0

Idea would to poke the backend every 2 seconds and expire the session when you stop for let's say 5 seconds? This way 3 to 5 seconds after closing the tab session would automatically expire.

setInterval( function() {
  $.get('/poke.php');
}, 2000); 

While php side:

// poke.php
$_SESSION['poke'] = time();

// Probably your index.php
if (isset($_SESSION['poke'] && time() - $_SESSION['poke'] > 5) {
   // Do the logout
} else {
  $_SESSION['poke'] = time();
}
Chris Cynarski
  • 493
  • 3
  • 9