Ladies and gents,
I found a very strange behavior which I cannot explain:
Assume that you have
- multiple form elements on your page, maybe rendered by php
- each form has one input field with an unique name
- on the beginning of that page a session will be started
- you store every posted input value in the $_SESSION variable
like this:
<?php
session_start();
$_SESSION["Test"] = "Hello";
foreach ($_POST as $name => $value) {
//echo "_POST: " . $name . ":" . $value . "<br>";
$_SESSION[$name] = $value;
//session_commit();
}
for ($i = 0; $i < 10; $i++) {
echo "<form action=\"multiform.php\" method=\"post\">Value for input $i: <input type=\"text\" name=\"input".$i."\"></form>\n";
}
print_r($_SESSION);
?>
If you use the above code, only the “Test” = “Hallo” will persist after the refresh of the page. Regardless which input value has been posted and stored into the session by the foreach, it will be gone after refresh.
Now the interesting part:
If you add a name to the form like this…
echo "<form name=\"form$i\" action=\"multiform.php\" method=\"post\">Value for input $i: <input type=\"text\" name=\"input".$i."\"></form>\n";
…the posted values will be stored then.
But why?
What has the form name to do with the persistence of the $_SESSION?
EDIT: If the input name only contains numbers, the problem seems to arraise:
<input type=\"text\" name=\"$i\">
Thanks for clarifyng this.
Jan
EDIT2:
If the accessor key for the $_SESSION array only contains numbers, php obviously does not persist the values, so something like this, won’t be stored:
<?php
session_start();
for ($i = 1; $i < 10; $i++)
{
$_SESSION[$i] = "Hello $i";
}
?>
The confusing part is, if you do a
print_r($_SESSION)
just after the for loop, it will show 1-10 with Hello 1..10…
Though, after refresh it’s gone…
Found at http://php.net/manual/en/session.examples.basic.php