$_SESSION被json_decode销毁

时间:2022-12-29 15:50:09

I'm using sessions in php to store cart data for a website I'm building. All the data is stored as json string and is encoded/decoded using json_encode/json_decode on either end.

我正在使用php会话来存储我正在构建的网站的购物车数据。所有数据都存储为json字符串,并在两端使用json_encode/json_decode进行编码/解码。

It appears that on one page, json_decode is erasing my session data which seems really odd. Here's the relevant bit of code which I've narrowed it down to:

在一个页面上,json_decode删除了我的会话数据,这看起来很奇怪。这里有一些相关的代码,我把它缩小到:

$cart_data = $_SESSION['cart'];
$cart = json_decode($cart_data, 1);

I've been var_dumping $_SESSION['cart'] when testing and it looks like json_decode is affecting it even though I'm not directly telling it (without the json_decode the dump appears as a string of json, with it it appears as arrays). This is resulting in the session being destroyed when the page is refreshed or navigated away from.

我在测试时一直在卸载$_SESSION['cart'],而且看起来json_decode正在影响它,尽管我没有直接告诉它(没有json_decode转储显示为json字符串,它以数组的形式出现)。这导致在刷新页面或从页面导航时销毁会话。

I have a feeling I'm missing something fairly simple but can't spot it

我有一种感觉,我错过了一些相当简单的东西,但我看不出来

1 个解决方案

#1


1  

It looks like you're running this script on a server with register_globals = on - that causes the variable $cart to be preregistered as a reference to $_SESSION['cart'] (weird, but true). Therefore you're writing the output of json_decode() directly into the session object.

看起来,您在一个带有register_globals = on的服务器上运行这个脚本,这导致变量$cart被预先注册为$_SESSION['cart'](奇怪,但是正确的)。因此,您正在将json_decode()的输出直接写入会话对象。

Best way to cure this is do deactivate register_globals or, if that is not possible, use a different variable name or unbind $cart with unset($cart); before assigning the new value.

解决这个问题的最佳方法是禁用register_globals,或者,如果不可能的话,使用不同的变量名或unbind $cart与unset($cart);在分配新值之前。

Read more in the docs: http://www.php.net/manual/en/reserved.variables.session.php#85448

阅读更多文档:http://www.php.net/manual/en/reserved.variables.session.php#85448

#1


1  

It looks like you're running this script on a server with register_globals = on - that causes the variable $cart to be preregistered as a reference to $_SESSION['cart'] (weird, but true). Therefore you're writing the output of json_decode() directly into the session object.

看起来,您在一个带有register_globals = on的服务器上运行这个脚本,这导致变量$cart被预先注册为$_SESSION['cart'](奇怪,但是正确的)。因此,您正在将json_decode()的输出直接写入会话对象。

Best way to cure this is do deactivate register_globals or, if that is not possible, use a different variable name or unbind $cart with unset($cart); before assigning the new value.

解决这个问题的最佳方法是禁用register_globals,或者,如果不可能的话,使用不同的变量名或unbind $cart与unset($cart);在分配新值之前。

Read more in the docs: http://www.php.net/manual/en/reserved.variables.session.php#85448

阅读更多文档:http://www.php.net/manual/en/reserved.variables.session.php#85448