17

How to get the currently logged in user's role in Drupal 7 ? Do you know a simple way of accomplish this ? Is there some drupal core functions for this?

Ek Kosmos
  • 4,050
  • 7
  • 28
  • 45

4 Answers4

25

You can access to the user roles by just using this PHP snippet:

<?php $GLOBALS['user']->roles; ?>
Artusamak
  • 2,283
  • 17
  • 17
25

$user->roles is an array of the roles that belong to the user keyed by the role ID, value is the role string. So if you wanted to check if user had role 'authenticated user' your code snippet would look something like this (not necessarily the most optimized approach, in_array is a fairly performance-expensive function):

global $user;

if (in_array('authenticated user', $user->roles)) {
     //do stuff here
}

Note that in_array can also accept an array as the "needle" (argument #1) so you could check against multiple role options:

in_array(array('authenticated user', 'anonymous user'), $user->roles);
mattacular
  • 1,839
  • 13
  • 17
  • 4
    On the second 'arrayed' needle snippit, [per the docs](http://php.net/manual/en/function.in-array.php) and a quick bit of test code, you are asking `in_array` to check to see whether or not `$user->roles` contains an array of `array('authenticated user', 'anonymous user')`, not the individual elements `'authenticated user'` or `'anonymous user'`. [array_intersect()](http://php.net/manual/en/function.array-intersect.php) would do the trick for that though. – Paul Mennega Sep 21 '12 at 17:06
9

I have found a interesting solution to check for multiple roles of a user:

global $user;
$check = array_intersect(array('moderator', 'administrator'), array_values($user->roles));
if (empty($check) ? FALSE : TRUE) {
    // is admin
} else {
    // is not admin
}
Ek Kosmos
  • 4,050
  • 7
  • 28
  • 45
1

// Load the currently logged in user.

 global $user;
 print_r($user->roles);//this gives you current user roles

//to check whether he is administrator, you can do so by

  if (in_array('administrator', $user->roles)) {
            // do some stuff
            $form['field_end_date']['#disabled'] = FALSE;
    }
Developer
  • 3,307
  • 4
  • 35
  • 42