Session variables seem not to be saved

2019-06-17 09:56发布

Quite simple code:

<?
session_start();
$_SESSION['t'.time()]     = "ok";
echo "<pre>".print_r($_SESSION, 1)."</pre>";
?>

shows, as expected, something like

Array
(
    [t1330966834] => ok
    [t1330966835] => ok
    [t1330966836] => ok
)

after 3page reloads.

Let's change a few symbols:

$_SESSION[time()]     = "ok";

(now without 't') and I expect after few reloads something like

Array
(
    [t1330966834] => ok
    [t1330966835] => ok
    [t1330966836] => ok
    [1330967020] => ok
    [1330967021] => ok
    [1330967022] => ok
    [1330967023] => ok
)

But actually the result is absolutely different:

   Array
    (
        [t1330966834] => ok
        [t1330966835] => ok
        [t1330966836] => ok
        [1330967020] => ok
    )

We have 3 previous array cells ad one and only one 'time' cell - no matter how many times you reload the page. The time is correct, it different each second but only one cell without 't'! Also I tried

$t =time();
$_SESSION[$t]     = "ok";

and even

$t =intval(time());
$_SESSION[$t]     = "ok";

But it's remains only one cell with time.

Tested at php 5.2.13 and 5.3.10 at 2 different servers. What am I doing wrong?

标签: php session time
3条回答
贪生不怕死
2楼-- · 2019-06-17 10:23

This is not a strange thing. It is simply skipping numeric keys. You can see this error, if you have enabled the notice to be displayed.

As mentioned on this comment on php.net. You should not use numeric keys to define values in session.

Quote

Careful not to try to use integer as a key to the $_SESSION array (such as $_SESSION[0] = 1;) or you will get the error "Notice: Unknown: Skipping numeric key 0. in Unknown on line 0"

查看更多
够拽才男人
3楼-- · 2019-06-17 10:32

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.

http://php.net/manual/en/session.examples.basic.php

查看更多
beautiful°
4楼-- · 2019-06-17 10:38

When cranking error_reporting way up, you should notice this:

Notice in <file>, line ...: session_write_close(): Skipping numeric key 1330967020

Numeric indeces to session variables are not supported.

查看更多
登录 后发表回答