PHP将$ _SESSION数据存储到变量中,始终会导致对会话对象的引用

我只需要调试生产php网站中的问题。这是原始开发人员假定$ cust_id = $ _SESSION ['cust_id'];的演示。是通过值传递的,但是以某种方式它是对会话对象的引用!

有人可以解释以下行为及其背后的原因,以及以后PHP开发人员可以做什么以免再次犯此错误。

代码:

<?php

        session_start();

        $_SESSION['cust_id'] = 1;           // sets $_SESSION['cust_id'] 1 = all good

        echo $_SESSION['cust_id'] . "<br>";    // returns 1 = all good

        $cust_id = $_SESSION['cust_id'];      // sets $cust_id 1 = all good     //note this is not =&

        echo $cust_id . "<br>";               // returns 1 = all good

        echo $_SESSION['cust_id'] . "<br>";    // returns 1 = all good

        $cust_id = 5;                          // He is going to use this variable for something else for a little bit. should be ok.

        echo $cust_id . "<br>";               // returns 5 = all good

        echo $_SESSION['cust_id'] . "<br>";    // He expected this to still hold 1,because he haden't changed the session variable at all
                                               // returns 5!!!  what the...  $cust_id wasn't a reference to the session object surely? the original developer didn't expect that.

        echo "phpversion: " . phpversion() . "<br>";

        echo "ini_get('register_globals'): " . ini_get('register_globals') . "<br>";

输出:

1
1
1
5
5
phpversion: 5.3.29
ini_get('register_globals'): 1
lijipeng123 回答:PHP将$ _SESSION数据存储到变量中,始终会导致对会话对象的引用

已解决:

一些php虚拟主机已将REGISTER_GLOBALS设为ON(在php.ini中)

这会导致$ _SESSION ['cust_id']也创建一个称为$ cust_id的内部变量

如果开发人员使用与会话名称不同的变量名,则不会发生此问题。我遍历了所有代码,并将所有变量名称重命名为与会话名称不同,现在,无论有没有该设置,该代码都与所有不同的php服务器兼容。

$ cust_id_another_name = $ _SESSION ['cust_id'];

从此示例中我可以清楚地看到,为什么REGISTER_GLOBALS OFF是减少事故的更好的主意。这就是为什么PHP 5.4现在默认情况下将其关闭,并且您无法更改它的原因。

本文链接:https://www.f2er.com/3159534.html

大家都在问