In PHP, why are my session variables persisted as references?

后端 未结 4 1737
醉话见心
醉话见心 2021-01-22 09:37

Here\'s the code. It\'s a simple operation to check that a session ID isn\'t being spoofed by verifying the IP address:

session_start();
$session_ip_address = $_         


        
4条回答
  •  失恋的感觉
    2021-01-22 10:06

    The only time your session variables are going to be references, is when you reference a session variable to another session variable (or if the original reference is still in scope).

    Per example:

    session_start();
    $x = 'foo';
    $_SESSION['x'] = &$x;
    

    This will give you:

    array(1) {
      ["x"]=>
      string(3) "foo"
    }
    

    While this:

    $x = 'foo';
    $_SESSION['x'] = $x;
    $_SESSION['y'] = &$_SESSION['x']; // reference to another $_SESSION var
    

    Or this:

    session_start();
    $x = 'foo';
    $_SESSION['x'] = $x;
    $_SESSION['y'] = &$x;
    var_dump($_SESSION); // reference still in scope
    

    Would give you:

    array(2) {
      ["x"]=>
      string(3) "foo"
      ["y"]=>
      &string(3) "foo"
    }
    

    Either way, doing this:

    session_start();
    $y = $_SESSION['y'];
    $y = 'bar';
    

    Will not modify the y session variable. In order to do that, you'd have to do:

    session_start();
    $y = &$_SESSION['y'];
    $y = 'bar';
    

提交回复
热议问题