tags:

views:

351

answers:

1

I always hear using global variables are dangerous. Does this apply to Drupal? Take a look at the following example:

function myFunction($bla) {
   global $user;
   if (isAuthenticated($user->uid)) {
        print $secretCode;
   }

}

Can this be hacked?

+3  A: 

Global variables can be dangerous for many reasons, some of which include:

  1. Clutters namespaces
  2. It makes maintenance difficult and encourages monkeypatching, as global variables can be modified from anywhere
  3. They are not referentially transparent
  4. In memory-managed languages, global variables can become the source of memory leaks
  5. They make debugging especially difficult in large applications/sites, as it can be difficult to track down where they are being set and modified.

Nothing is particularly threatening about your use case. It should be fine. If you're very scared, you can ensure that $user->uid is an integer before evaluating:

function myFunction($bla) {
   global $user;
   if( is_int($user->uid) ){
      if (isAuthenticated($user->uid)) {
         print $secretCode;
      }
   }
}

But this is probably unnecessary.

cpharmston
Do you perhaps know if it's dangerous in my specific example? I know that $user is a built-in variable. I.e. I don't define it, Drupal does.
RD
Edited my answer a bit.
cpharmston
One more question. Is there no way that a "hacker" can pass in his own uid? I mean, if he could pass in a uid of 1, that would mean he's admin.
RD
I haven't done much more than theming in Drupal, but IIRC, $user is only set when a user successfully logs in. If someone is able to hack that, the problem is much bigger than using globals :)
cpharmston