0

Is the use of the $GLOBALS array in Drupal in anyway 'less secure' or 'bad practice'. Like using:

$GLOBALS['user']->uid

instead of

$account->uid

if it were avialable?

Thanks.

2 Answers 2

2

Short answer is no it is not bad practice or insecure, it is fine to use the $user global. Drupal core and a huge amount of modules use the $user global.

If you want to be really picky though:

However, it is possible for you to install bad code into your site somewhere that puts bad things into the $user global.

That is just a risk in general though with putting any code on your site, it doesn't just relate to the $user global.

Also, for all I know the $account variable you talk about could be bad because I have no idea where that variable is coming from as your question doesn't detail it.

3

Directing using

global $user
$user->uid

adds a new variable to your current scope, which adds potential for misuse and other accidents.

Using

$GLOBALS['user']->uid

can be seen as a safety precaution. You can still mess things up, but it is somewhat harder, and you don't introduce a new variable.

However, directly poking around in the $user object is bad in a lot of cases, especially explicitly using $user->uid.

Whenever possible, you should leverage the API. For example, use

if (user_is_logged_in()) { ... }

instead of

global $user;
if ($user->uid) { ... }

and use user_access() instead of using $user->roles.

One place where explicit $user->uid use may be needed is with database queries, though that can be lessened somewhat with EntityFieldQuery->addAccount and db_select->addtag('node_access').

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.