Destroy PHP session on page leaving

I need to destroy a session when user leave from a particular page. I use session_destroy() on the end of the page but its not feasible for me because my page has pagination. My page is: abc.php?page=1 or abc.php?page=2 or abc.php?page=3.

So, I need to destroy a session when a user leaves from abc.php page. How can I do it without using a cookie?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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']) {
        ### 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.

Solution 2

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 .

Solution 3

I had a similar issue but mine was on a page reload I wanted variables that I had printed to be destroyed. It was for my login for my web design class I was making error feed back for if user put in a bad username or password. I could get the error to display but if I hit refresh page they errors would just stay there. I found that by just setting the variable to nothing after it printed would kill it. Take a look at what i did:

<p>To access my website please Login:</p>
<form name='login' action="./PHP_html/PHP/login.php" method='post'>
Username: <input type='text' name='username' /><div><?php print $_SESSION['baduser']; $_SESSION['baduser'] = "";?></div><br />
<div style="padding-left: 4px">Password: <input type='password' name='password' /><div><?php print $_SESSION['badpass']; $_SESSION['badpass'] = "";?></div></div>
<input type='submit' value='Login' /> or you can <a href="./Terms.php" rel="nofollow noreferrer noopener">Register</a>

I don’t know if this helps at all but it worked for me.

Also, thanks to all you that post on sites like this to help those of us who are still learning.

Solution 4

For a particular page you need to destroy the session, then unset the all session variable


For the whole site you can use session_destroy();

Solution 5

I solve the problem.First take the current url then chk the page stay on current url.if page is not in the current url then destroy the session.

$url = "http" . ((!empty($_SERVER['HTTPS'])) ? "s" : "") . "://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
if (!preg_match("/$page_name/",$url)) 

But this code should be used on another pages.Because http is a stateless processes so no way to find when a user leave the page.

Solution 6

You can’t tell when a user navigates away from the page, it’s simply not possible in any reliable manner.

The best you can do is exploit how cookies work. When starting a session, you’re sending a cookie to the client which identifies the client on each subsequent visit, and hence activates the associated session. It is up to the client to send this identification on subsequent visits, and it’s up to the client to “forget” his identification.

You can instruct the client to only send the cookie for certain pages, and you can instruct him to forget the cookie when closing the browser (with a lifetime of 0). This can be set using session_set_cookie_params.

Other than that, you can simply ignore the session parameters on pages where they don’t matter. You can delete the session (or certain values of it) after some time of inactivity when you assume the client has left.

Solution 7

Borealid deserves credit for pointing to the most elegant solution.

A more kludgey solution is to keep an iframe on the page that is pointed to another “monitor” page which is set to refresh every few seconds. This can be done without JavaScript using:

<meta http-equiv="refresh" content="10">

This refreshes the monitor page every 10 seconds. When this happens, the monitor page can record the time (overwriting the previously recorded time) and session ID on the server somewhere (DB or file).

Then you would have to create a cronjob that checks the file/DB for any sessions that are more than 10~12 seconds old and delete them manually. The session data is usually stored in a directory (specified by your PHP config) in a file named sess_the-session-ID. You could use a PHP function like this:

function delete_session($sessId) {
    $sessionPath = session_save_path();
    // you'll want to change the directory separator if it's a windows server
    $sessFile = "$sessionPath/sess_$sessId";
    if (file_exists($sessFile) && unlink($sessFile)) return true;
    return false;

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply