phpsession-variablessessionid

can a php $_SESSION variable have numeric id thus : $_SESSION['1234’]


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?


Solution

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

    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:

    <?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. The session engine itself prevents the numeric session keys from being saved to the session rather than PHP variable naming rules.