Anim8r
Anim8r

Reputation: 191

Why Does "GET" Override "SESSION"

In the code:

<?php
    session_start();
    $_SESSION['id'] = 14;
    if(isset($_GET['id']))
    {
        $id = $_GET['id'];
    }
    else
    {
        $id = $_SESSION['id'];
    }
    echo $id;
    echo "<br>";
    echo $_SESSION['id'];
?>

Why is the second value echoed out always equal the GET variable (assuming there is one set)? Is this a misconfiguration or am I missing something?

Upvotes: 2

Views: 309

Answers (1)

goat
goat

Reputation: 31823

My magic crystal ball says that you have the register_globals setting turned on. check it by calling phpinfo()

When register_globals is on, $foo and $_SESSION['foo'] are references to each other, but only if $foo is in the global scope. This means assigning a value to either of them, causes the other to update. Think of them as being the exact same variable.

That setting is ancient. If I remember correctly, the references between $foo and $_SESSION['foo'] will only be established after one of:

  1. immediately after calling session_start() IF $_SESSION['foo'] existed in the session.
  2. immediately after assigning any value to $_SESSION['foo']
  3. immediately after calling session_register('foo')

You should strongly consider disabling register_globals. unexpected program behavior just like this is the very reason the setting was discouraged, and eventually totally removed from php.

Upvotes: 6

Related Questions