Destroy PHP session on page leaving

To trigger when the user actually leaves the page, you must use Javascript to send an asynchronous request back to the server. There's no way for the server to magically know the user has "left" a page.

See http://hideit.siteexperts.com/forums/viewConverse.asp?d_id=20684&Sort=0 .


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.

Tags:

Php

Session