php $ _SESSION变量可以具有数字ID吗:$ _SESSION ['1234'] [英] can a php $_SESSION variable have numeric id thus : $_SESSION['1234’]

查看:224
本文介绍了php $ _SESSION变量可以具有数字ID吗:$ _SESSION ['1234']的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在为这个问题发疯.

I've been driving myself nuts with this problem.

我正在动态创建一个会话ID,以便在刷新时保留页面状态.

I'm creating a session id dynamically in order to retain the page state on refresh.

如果单击页面元素,我将获取该元素的ID并将其传递给我的服务器端脚本,该脚本将创建会话变量:

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; 

很奇怪,这仅在某些时间有效,我将其范围缩小为以下事实:某些元素具有纯数字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;
};

在上面的示例中,只有非数字会话ID可见.例如,我可以echo $_SESSION['test'];完全没有问题.

In the example above only non-numeric session IDs were visible. For example I could echo $_SESSION['test']; with no issue at all.

有什么想法吗?

推荐答案

摘自手册: The keys in the $_SESSION associative array are subject to the same limitations as regular variable names in PHP, i.e. they cannot start with a number and must start with a letter or underscore. For more details see the section on variables in this manual.

在会话中使用纯数字键将不起作用.如果是数字,则可以尝试在其前加上下划线.

Using purely numeric keys in a session will not work. If it is numeric you can try preceding it with an underscore.

自2015年10月的PHP 5.5.9起,尽管不再出现手册参考,但这仍然是正确的.

As of PHP 5.5.9 in October 2015, this appears to still be true despite the manual reference no longer appearing.

测试代码:

<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();
$_SESSION['a123'] = 'a123';
$_SESSION['123'] = '123str';
$_SESSION[455] = '455int';
$_SESSION['_123'] = '_123';

收益:

注意:未知:在第0行的未知"中跳过数字键123

Notice: Unknown: Skipping numeric key 123 in Unknown on line 0

注意:未知:在第0行的未知"中跳过数字键455

Notice: Unknown: Skipping numeric key 455 in Unknown on line 0

然后var_dump($_SESSION);仅显示:

array(2) {
  ["a123"]=>
  string(4) "a123"
  ["_123"]=>
  string(4) "_123"
}

当会话数据在请求结束时被序列化时,实际上似乎发生了这种情况.此处.显然,会话引擎本身会阻止将数字会话密钥保存到会话中.

This actually appears to happen when the session data gets serialized at the end of the request here. Apparently the session engine itself prevents the numeric session keys from being saved to the session.

这篇关于php $ _SESSION变量可以具有数字ID吗:$ _SESSION ['1234']的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆