sikas
sikas

Reputation: 5523

Destroy PHP Session on closing

I have created a simple login page which is based on the sessions.

session_start();

and added a logout page that contains this

session_destroy();

Now when I close the browser/page and reopen it, the values of the session are still there.

I want to know how to completely destroy the session on page/browser close.

Upvotes: 17

Views: 62192

Answers (5)

csandreas1
csandreas1

Reputation: 2378

If the session exists, log out by destroying the session and redirecting the user to the home page. A temporary cookie was used to store the session identity. This cookie is also destroyed.

<?php
    // This is the logout page for the site.
    session_start();//access the current session.
    //if no session variable then redirect the user
    if (!isset($_SESSION['user_id'])) {
    header("location:index.php");
    exit();
    }else{ //cancel the session
        $_SESSION = array(); // Destroy the variables
        session_destroy(); // Destroy the session
        setcookie('PHPSESSID', ", time()-3600,'/', ", 0, 0);//Destroy the cookie
        header("location:index.php");
        exit();
    }
    ?>

Upvotes: 0

Fahmi
Fahmi

Reputation: 11

Server can't detect browser or tab closed, you could use Javascript or Ajax but sorry I don't have knowledge about that.

My suggestion is use Session Timeout, so session will be destroyed if there's no action from user. This is an example :

// destroy every 2 minutes

if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 120)) {
    // last request was more than 2 minutes ago
    session_destroy();   // destroy session data in storage
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp

// end of code

Hope this help you

Upvotes: 0

Giwayshans
Giwayshans

Reputation: 1

to remove session variables - session_unset();

to destroy the session - session_destroy();

session_unset();
session_destroy();

Upvotes: -1

superfro
superfro

Reputation: 3302

if you use:

session_set_cookie_params(0);
session_start();

Your session cookie will destroy when the browser is closed... so your session will be good until they close the browser. IE. You login, and you are logged in, you close the browser, re-open it, go to the site again, and you wont be logged in.

Upvotes: 26

Treffynnon
Treffynnon

Reputation: 21553

You will only be able to detect if the browser window has been closed using javascript at which point you might be able to trigger an Ajax request to perform a logout action.

Upvotes: 5

Related Questions