How to destroy session on closing the tab in php?

Member

by domenico , in category: PHP General , 10 months ago

How to destroy session on closing the tab in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elisha_langworth , 10 months ago

@domenico 

To destroy a PHP session when the tab is closed, you can use JavaScript to handle the event of the tab being closed and make a request to a PHP script that destroys the session.


Here is a simple implementation:

  1. Add the following JavaScript code to detect when the tab is being closed:
1
2
3
4
5
6
window.onbeforeunload = function() {
   // Make an AJAX request to a PHP script to destroy the session
   var xhr = new XMLHttpRequest();
   xhr.open('GET', 'destroy_session.php', true);
   xhr.send();
}


  1. Create a PHP script destroy_session.php that will destroy the session:
1
2
3
4
5
6
7
8
9
<?php
session_start();

// Unset all session variables
$_SESSION = array();

// Destroy the session
session_destroy();
?>


  1. Make sure to include the JavaScript code in your HTML file before the closing tag.


With this implementation, whenever a user closes the tab, the JavaScript code will make a request to the destroy_session.php script which will destroy the session.