Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Session variables seem not to be saved

Tags:

php

time

session

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?

like image 315
Putnik Avatar asked Mar 05 '12 17:03

Putnik


People also ask

How are session variables stored?

By default, session data is stored in the server's /tmp directory in files that are named sess_ followed by a unique alphanumeric string (the session identifier).

Can we save data permanently using session variables?

Session variables contain data about the current user. They are accesible to all pages contained in a single web application. Session data is not permanent, but you can load permanent user data for particular users using databases.

Are session variables secure?

By default, session variables are created with the secure flag set to true. If any secure variables are saved to the database, you must type your password, which is used as the encryption key.

What should not be stored in session?

Things like Database Data such as User Rows should not be stored in the session and you should create a separate cache mechanism to do this for you. Save this answer.


2 Answers

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

like image 141
juanrpozo Avatar answered Oct 26 '22 07:10

juanrpozo


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.

like image 44
Linus Kleen Avatar answered Oct 26 '22 07:10

Linus Kleen