Benjamin
Benjamin

Reputation: 2123

How to unset/destroy all session data except some specific keys?

I have some session data in a website. I want to destroy all session data when user click another page, except some specific keys like $_SESSION['x'] and $_SESSION['y'].

Is there a way to do this?

Upvotes: 6

Views: 15957

Answers (5)

Ibrahim Azhar Armar
Ibrahim Azhar Armar

Reputation: 25745

to unset a particular session variable use.

unset($_SESSION['one']);

to destroy all session variables at one use.

session_destroy()

To free all session variables use.

session_unset();

if you want to destroy all Session variable except x and y you can do something like this.

$requiredSessionVar = array('x','y');
foreach($_SESSION as $key => $value) {
    if(!in_array($key, $requiredSessionVar)) {
        unset($_SESSION[$key]);
    }
}

Upvotes: 5

Gumbo
Gumbo

Reputation: 655219

As $_SESSION is a regular array, you can use array_intersect_key to get your resulting array:

$keys = array('x', 'y');
$_SESSION = array_intersect_key($_SESSION, array_flip($keys));

Here array_flip is used to flip the key/value association of $keys and array_intersect_key is used to get the intersection of both arrays while using the keys for comparison.

Upvotes: 3

Griminvain
Griminvain

Reputation: 95

So when i can't ask i will answer:

This question is old but still someone is reviewing this like me i searched and i liked one of the answers but here is a better one: Lets unset $array1 except some variables as $array2

function unsetExcept($array1,$array2) {
    foreach ($array1 as $key => $value)
        if(!in_array($key, $array2)){
            unset($array1[$key]);
        }
    }
}

Why is this better ? IT'S NOT ONLY FOR $_SESSION

Upvotes: -2

Vladimir
Vladimir

Reputation: 836

Will this help?

function unsetExcept($keys) {
  foreach ($_SESSION as $key => $value)
    if (!in_array($key, $keys))
      unset($_SESSION[$key]);
}

Upvotes: 2

Fad
Fad

Reputation: 9858

Maybe do something like this

foreach($_SESSION as $key => $val)
{

    if ($key !== 'somekey')
    {

      unset($_SESSION[$key]);

    }

}

Upvotes: 26

Related Questions