php $_SESSION 变量可以有数字 id 吗: $_SESSION['1234’]
我一直被这个问题逼疯了。
我正在动态创建会话 ID,以便在刷新时保留页面状态。
如果单击页面元素,我会获取该元素的 id 并将其传递给创建会话变量的服务器端脚本:
$_SESSION[$id] = $id;
奇怪的是,这仅在某些时候有效,我将其范围缩小到以下事实:某些元素具有纯数字 ID,而其他 ID 则不然:
if (is_numeric($id))
{
$_SESSION[$id] = $id;
$_SESSION['test'] = $id;
}else{
$_SESSION[$id] = $id;
};
在上面的示例中,只有非数字会话 ID 可见。例如,我可以 echo $_SESSION['test'];
没有任何问题。
有什么想法吗?
I've been driving myself nuts with this problem.
I'm creating a session id dynamically in order to retain the page state on refresh.
If a page element is clicked, I take the id of the element and pass it to my server side script which creates the session variable:
$_SESSION[$id] = $id;
Bizarrely, this was working only some of the time, I narrowed it down to the fact that some elements have a purely numeric id and others do not:
if (is_numeric($id))
{
$_SESSION[$id] = $id;
$_SESSION['test'] = $id;
}else{
$_SESSION[$id] = $id;
};
In the example above only non-numeric session IDs were visible. For example I could echo $_SESSION['test'];
with no issue at all.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从手册中:
在会话中使用纯数字键是行不通的。如果它是数字,您可以尝试在其前面添加下划线。
编辑:从 2015 年 10 月的 PHP 5.5.9 开始,尽管手动参考不再出现,但这似乎仍然是正确的。
编辑 2:截至 2023 年 12 月,对于 PHP 8.1.14 和 PHP 8.3.0-RC1。
PHP 警告:未知:在第 0 行的未知中跳过数字键 123
测试代码:
产量:
然后
var_dump($_SESSION);
仅显示:这实际上似乎发生在会话数据在请求结束时被序列化。会话引擎本身会阻止数字会话密钥保存到会话中,而不是 PHP 变量命名规则。
From the manual:
Using purely numeric keys in a session will not work. If it is numeric you can try preceding it with an underscore.
EDIT: As of PHP 5.5.9 in October 2015, this appears to still be true despite the manual reference no longer appearing.
EDIT 2: This is still true as of December 2023 for PHP 8.1.14 and PHP 8.3.0-RC1.
PHP Warning: Unknown: Skipping numeric key 123 in Unknown on line 0
Test code:
Yields:
Then a
var_dump($_SESSION);
shows only:This actually appears to happen when the session data gets serialized at the end of the request. The session engine itself prevents the numeric session keys from being saved to the session rather than PHP variable naming rules.
$_SESSION
中的顶级键不能是数字,但更深级别的键可以。例如。
Top level keys in the
$_SESSION
can't be numeric, but keys on the deeper level can.Eg.
使用全数字元素 id(即
)是一种不好的做法 - 您应该至少放置一个字母字符,例如
。这应该可以解决您的问题 - 或者您可以在创建会话时添加字母字符,然后在刷新页面时将其删除:
$_SESSION[$id] = substr($str, 0, 1);
It's bad practise to have an all numeric element id (i.e.
<div id="123">
) - you should place at least one alpha character, e.g.<div id="e123">
. This should solve your problem - alternatively you can just add the the alpha character when creating the session then remove it if the page is refreshed:$_SESSION[$id] = substr($str, 0, 1);