Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

session

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?

like image 237
Benjamin Avatar asked Aug 27 '11 11:08

Benjamin


2 Answers

Maybe do something like this

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

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

      unset($_SESSION[$key]);

    }

}
like image 101
Kemal Fadillah Avatar answered Oct 04 '22 04:10

Kemal Fadillah


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]);
    }
}
like image 29
Ibrahim Azhar Armar Avatar answered Oct 04 '22 04:10

Ibrahim Azhar Armar