5

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?

Gumbo
  • 643,351
  • 109
  • 780
  • 844
Benjamin
  • 2,073
  • 4
  • 18
  • 16

5 Answers5

25

Maybe do something like this

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

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

      unset($_SESSION[$key]);

    }

}
Kemal Fadillah
  • 9,760
  • 3
  • 45
  • 63
5

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]);
    }
}
Community
  • 1
  • 1
Ibrahim Azhar Armar
  • 25,288
  • 35
  • 131
  • 207
3

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.

Kemal Fadillah
  • 9,760
  • 3
  • 45
  • 63
Gumbo
  • 643,351
  • 109
  • 780
  • 844
2

Will this help?

function unsetExcept($keys) {
  foreach ($_SESSION as $key => $value)
    if (!in_array($key, $keys))
      unset($_SESSION[$key]);
}
Vladimir
  • 818
  • 5
  • 13
  • Yes it is. But i was searching a spesific function in Session Functions. Thanks, i will do this way. Also thanks @Kemal Fadillah for original loop. – Benjamin Aug 27 '11 at 12:04
-2

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

Griminvain
  • 95
  • 1
  • 10