How to disconnect / destroy all session data except some certain keys?

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

Is there any way to do this?

+4
source share
5 answers

Maybe something like this

 foreach($_SESSION as $key => $val) { if ($key !== 'somekey') { unset($_SESSION[$key]); } } 
+16
source

to disable the use of a specific session variable.

 unset($_SESSION['one']); 

to destroy all session variables in one use.

session_destroy()

To free all session variables, use.

session_unset();

if you want to destroy the entire 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]); } } 
+4
source

Since $_SESSION is a regular array, you can use array_intersect_key to get the resulting array:

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

Here array_flip used to switch the key / value associations of $keys and array_intersect_key used to get the intersection of both arrays when using keys for comparison.

+4
source

Did it help?

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

Therefore, when I can not ask, I will answer:

This question is old, but still someone is looking at it like I did, I searched and I liked one of the answers, but here is the best one: Allows unset $ array1, except for some variables like $ array2

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

Why is it better? THIS IS NOT ONLY FOR $ _SESSION

-2
source

Source: https://habr.com/ru/post/1369283/


All Articles