Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - foreach affects session value

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

like image 612
Deluxe Avatar asked May 15 '26 14:05

Deluxe


1 Answers

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.

like image 158
cletus Avatar answered May 18 '26 02:05

cletus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!