问题
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?
回答1:
From the manual:
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.
EDIT: As of PHP 5.5.9 in October 2015, this appears to still be true despite the manual reference no longer appearing.
Test code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
$_SESSION['a123'] = 'a123';
$_SESSION['123'] = '123str';
$_SESSION[455] = '455int';
$_SESSION['_123'] = '_123';
Yields:
Notice: Unknown: Skipping numeric key 123 in Unknown on line 0
Notice: Unknown: Skipping numeric key 455 in Unknown on line 0
Then a var_dump($_SESSION);
shows only:
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.
回答2:
Top level keys in the $_SESSION
can't be numeric, but keys on the deeper level can.
Eg.
$_SESSION['ids'][13] = $foo;
$_SESSION['ids'][666] = $bar;
回答3:
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);
来源:https://stackoverflow.com/questions/7450371/can-a-php-session-variable-have-numeric-id-thus-session1234