views:

216

answers:

1

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 some 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].

+12  A: 

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.

cletus
+1 : nice catch ! I wasn't understanding how the described problem could occur, and didn't think about register_global -- after setting register_global=On, I reproduce the problem ^^ ;; and if I could, I would give you another +1 for "you shouldn't use register globals"
Pascal MARTIN
+1 for seeing what was going on. The unquoted array key was a bit of a red-herring.
Derek Illchuk
+1 I didn't know about register_globals, thanks for explaining it!
dusan
+1 Well done. I had forgotten about register_globals.
Pekka