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

后端 未结 5 1182
清酒与你
清酒与你 2020-12-19 10:59

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

相关标签:
5条回答
  • 2020-12-19 11:41

    Will this help?

    function unsetExcept($keys) {
      foreach ($_SESSION as $key => $value)
        if (!in_array($key, $keys))
          unset($_SESSION[$key]);
    }
    
    0 讨论(0)
  • 2020-12-19 11:43

    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.

    0 讨论(0)
  • 2020-12-19 11:49

    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

    0 讨论(0)
  • 2020-12-19 11:50

    Maybe do something like this

    foreach($_SESSION as $key => $val)
    {
    
        if ($key !== 'somekey')
        {
    
          unset($_SESSION[$key]);
    
        }
    
    }
    
    0 讨论(0)
  • 2020-12-19 11:51

    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]);
        }
    }
    
    0 讨论(0)
提交回复
热议问题