SESSION being destroyed by json

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.

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:

$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.

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


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.

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.

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

链接地址: http://www.djcxy.com/p/60232.html

上一篇: 会话未恢复

下一篇: SESSION被json销毁