How can foreach loop affect session variable?
session_start();
$_SESSION[test] = "Session content";
echo $_SESSION[test].'<br />';
$test_array = array("test", "array", "something", "array end");
foreach($test_array as $test){
echo $test.'<br />';
}
echo '<br />Session content after foreach: '.$_SESSION[test].'<br />';
When I run this code on s开发者_Go百科ome web hostings, its output is OK.
Session content
test
array
something
array end
Session content after foreach: Session content
But only at first execution (when session is created). When I execute this code second time (session is already created) its output looks like this:
Session content
test
array
something
array end
Session content after foreach: array end
I don't know how can variable $test affect $_SESSION[test].
I'd bet you're using register globals and that means that if you have a session variable named test
it will become a global variable named $test
when you execute session_start()
. Your loop then changes the value of $test
, which is a global reference to the session variable.
See Using Register Globals and the register_globals directive.
Basically this is a good lesson why you shouldn't use register globals. In this case the name clash is probably harmless but you can potentially create huge problems this way, even vulnerabilities to attacks.
精彩评论