通过引用取消会话无效

时间:2019-04-12 01:03:09

标签: php session reference unset

我正尝试通过某个功能取消设置会话,因此更容易。 我正在这样调用函数:unsetSession("index1/index2/index3/...)

当我提供到最后一个元素的完整路径时,它可以工作。但是,当我要删除包含更多元素的元素时,它不起作用。

示例:

$_SESSION

["test"]=>
array(1) {
  ["value1"]=>
  array(1) {
    ["value2"]=>
    string(6) "String"
  }
} 

此操作:unsetSession("test/value1/value2")将起作用并删除value2。 这:unsetSession("test/value1")无法正常工作。那是我的问题。

代码:

PUBLIC function unsetSession($s) {

        if (!strstr($s, "/")) {

            unset($_SESSION[$s]);

        } 
        else {

            $temp = &$_SESSION;

            $path = explode('/', $s);

            if (!isset($temp[current($path)]) OR is_string($temp[current($path)])) return false;
            $temp = &$temp[current($path)];

            while ($next = next($path)) {

                if ((isset($temp[$next]) OR $temp[$next] == null) AND !is_array($temp[$next])) {

                    unset($temp[$next]);
                    return true;

                }

                $temp = &$temp[$next];

            }

            unset($temp); // <- DOES NOT UNSET SESSION, why?
            return true;

        }

        return false;

    }

有人知道为什么那行不通吗?

1 个答案:

答案 0 :(得分:0)

我将使用current()和next()代替函数end(),该函数提供数组的最后一个元素:

   function unsetSession($s) {
    if (!strstr($s, "/")) {
        unset($_SESSION[$s]);
    } else {
        $path = explode('/', $s)
        unset(end($path));
    }
    return false;
    }