Strange PHP Session behaviour. PHP overwrites $_SESSION['var'] with $var
I have this small PHP script:
<?php
session_start();
$var = array();
$var['key'] = 'Var -&g开发者_如何学Got; Key';
if ($_GET['set']) {
$_SESSION = array();
$_SESSION['var'] = 'Session -> Var';
}
print_r($_SESSION);
?>
I would expect it to return this, for set=0 and set=1:
Array
(
[var] => Session -> Var
)
However it returns this for set=0 (after set=1 of course):
Array
(
[var] => Array
(
[key] => Var -> Key
)
)
Have a look yourselfe over here: http://dev.gruppenunterkuenfte.de/index_test.php?set=1
What seams to happen is that $_SESSION['var'] gets replaced by $var. But only after the next page load.
Any idea why?
I can switch my PHP version in my hosters admin interface and I tried 5.2.11, 5.3.2 and 4.4.8.
Is it a setting I can change in PHP, so it will not overwrite Session Variables? Cause I don't have this issue on another server.
There seams to be some kind of setting to make PHP write $var in $_SESSION['var'], if $_SESSION['var'] is defined.
Turn off register_globals
option
nothing strange, it's documented behavior.
just turn register_globals
off
$_SESSION['var'] = 'x';
this creates an underlying $var = 'x';
and because RegisterGlobals is ON in your php.ini or php server settings, then your other php pages and functions can also see $var.
if you set $var = 'y'; then $_SESSION['var'] instantly becomes 'y'
PHP directive register_globals went from ON to OFF in PHP » 4.2.0.
This feature has been DEPRECATED as of PHP 5.3.0
and register_globals has been REMOVED as of PHP 5.4.0
Solution: keep the names of $var and $_SESSION['var'] separate, like:
$myvar = array(); //not $var = array();
_SESSION['var'] = anyobject;
This way, your code will be compatible, no matter what settings the php host server has set.
精彩评论