Question

I came across some strange session behavior today while testing some things out. First off, I've been tasked to create a registration feature for a WordPress website. I've done a fair amount of work in WordPress in the past, but I've never done anything involving any server-side scripting languages.

I was testing out my work environment, which involves making sure that I'm able to connect to MySQL, making sure sessions are working, and basically just familiarizing myself with the setup.

When testing sessions, I did the following:

<?php
$timer = time();

$_SESSION[$timer] = $timer;

print_r($_SESSION);
?>

I was expecting on the first load of the page to see something like this:

Array
(
    [1396745563] => 1396745563
)

... which is exactly what happened. On the second refresh, I wanted to see:

Array
(
    [1396745563] => 1396745563
    [1396745570] => 1396745570
)

... But instead, I saw:

Array
(
    [1396745570] => 1396745570
)

Wow! The original session variable for timestamp 1396745563 was gone, and there was a new one in it's place.

My immediate reaction was that maybe a session_start() was missing, but that was not the case. Just to further convince myself that something was weird about this, I altered my code to look like this:

<?php
$timer = time();

$_SESSION['time_' . $timer] = $timer;

print_r($_SESSION);
?>

I thought that perhaps having a session variable with a timestamp for an index had some sort of special behavior (which might be the answer to this question for all I know).

This time, the behavior was exactly as I had expected. Each refresh of the page added on to the array print-out. After a few refreshes of the page, it looked something like this:

Array
(
    [time_1396745663] => 1396745663
    [time_1396745667] => 1396745667
    [time_1396745671] => 1396745671
    [time_1396745675] => 1396745675
    [1396745570] => 1396745570
)

That oddball variable is the session data that carried over from my original attempt (I'm just being precise).

Can someone explain this extremely odd behavior? I can't think of anything obvious that I could have done that would have caused this.

Note: I doubt that this has anything to do with WordPress; I only included it to give a motive behind doing this.

Was it helpful?

Solution

The keys of $_SESSION adhere to the same rules as valid variable names in PHP. They must begin with a letter or an underscore, followed by any number of letters, numbers or underscores. Therefore, the output of time() can’t serve as a key unless it’s prefixed by at least one letter or underscore.

Add the line error_reporting(E_ALL); to your code and PHP will throw a notice like the following:

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top