tags:

views:

133

answers:

3

I really wondering about this code

<?    
  session_start()
 $_SESSION['me'] = 654;
    $me = $_GET['me'];

    echo  $_SESSION['me'];
?>

it will print the $me value not the $_SESSION['me'] value.

Are this is a bug or they do it for security reasons ? any Explanations ?

+3  A: 

Are you calling session_start() anywhere?

If not, than php is probably second guessing what you mean so you can check the error log to see what is happening exactly.

jeroen
sure , I called session_start();
Waseem Abu Senjer
Before any output is sent to the browser?
jeroen
+5  A: 

Do you have register_globals enabled by any chance?

Edit: This seems to have to do with the famous session side-effect that existed until PHP 4.3. If a session variable is not initialized, the value of a possibly existing global variable of the same name will be used.

PHP versions 4.2.3 and lower have an undocumented feature/bug that allows you to initialize a session variable in the global scope, albeit register_globals is disabled. PHP 4.3.0 and later will warn you, if this feature is used, and if session.bug_compat_warn is also enabled. This feature/bug can be disabled by disabling this directive.

I still can't quite get my head around why exactly this happens, though. And what pygorex1 writes in his answer makes it even weirder.

Pekka
Ok , i set register_globals = Off ,and the code work true and print the $_SESSION value , but when set register_globals = On , the code print the $me value , Why ?
Waseem Abu Senjer
@wseem check my updated answer.
Pekka
+3  A: 

I'm able to to recreate this behavior using PHP v5.2.10 with register_globals and after multiple visits to the page:

test.php:

<?php
session_start();
$_SESSION['me'] = 654;
$me = $_GET['me'];
echo  $_SESSION['me'];

http://localhost/test.php?me=321

The first time the page is loaded the output is 654. The second time the page is run the output becomes 321. Why does this happen?

First Time:

  • When first called the $_SESSION['me'] variable doesn't exist, so it is NOT initialized as a global.
  • $_GET['me'] does exist and is initialized as global variable $me

Second Time:

  • On page refresh the $_SESSION['me'] variable now exists and is initialized as the global var $me
  • $me now refers to $_SESSION['me']
  • Any assignment to $me will overwrite the session variable, so the SESSION variable becomes 321 and the output becomes 321

However, the OP states in a comment that he has register_globals turned off ... in that case I'm not sure what to make of it!

pygorex1
yes , this is exactly what is happened
Waseem Abu Senjer