46

How can I check if a user has a certain role?

I found this but it is for Drupal 6.

11 Answers 11

92

Since you already found that post, make sure you also read the comments. It clearly explains why checking for a permission is recommended over checking for a role. When you use permissions, you can assign that permission to multiple roles, which makes your system more flexible. Also, remember that roles can be renamed, which would break your code.

That said, if you want to check for a role, you can do this:

// Load the currently logged in user.
global $user;

// Check if the user has the 'editor' role.
if (in_array('editor', $user->roles)) {
  // do fancy stuff
}
2
  • 1
    What if I want to check more than 1 role. e.g. If "editor" or "publisher" than do fancy stuff. How to code. Pls advise. Can't figure out really.
    – Adamtan
    May 15 '13 at 10:04
  • 9
    Please read the answer: it's not recommended to check for a role (or more than one). Check for permissions instead. The rest of your question (combining two conditions in an if-statement) is basic PHP, nothing Drupal-related. Read the PHP documentation on logical operators. May 15 '13 at 18:47
12

To check if the current user has a single role or any of multiple roles, a great way is to do:

//can be used in access callback too
function user_has_role($roles) {
    //checks if user has role/roles
    return !!count(array_intersect(is_array($roles)? $roles : array($roles), array_values($GLOBALS['user']->roles)));
};

if (user_has_role(array('moderator', 'administrator'))) {
  // $user is admin or moderator
} else if(user_has_role('tester')){
  // $user is tester
} else{
  // $user is not admin and not moderator
}
1
10

Update for Drupal version >= 7.36

You can use function user_has_role from Drupal API https://api.drupal.org/api/drupal/modules%21user%21user.module/function/user_has_role/7.

Try this example:

<?php
function MYMODULE_foo() {
  $role = user_role_load_by_name('Author');
  if (user_has_role($role->rid)) {
    // Code if user has 'Author' role...
  }
  else {
    // Code if user doesn't have 'Author' role...
  }

  $user = user_load(123);

  if(user_has_role($role->rid, $user)) {
    // Code if user has 'Author' role...
  }
  else {
    // Code if user doesn't have 'Author' role...
  }
}
?>
2

Here's the actual code from the comment that is referred to in the accepted answer as the best practice

<?php
  function mymodule_perm() {
    return array('access something special');
  }

  function dosomethingspecial() {
    // For current user
    if (user_access('access something special')) {
      // Doing something special!
    }

    // For a specific user
    if (user_access('access something special', $theuser)) {
      // Doing something special!
    }
  }
?>
2

You could install Devel module and do dpm($user). This will print an array with all user information including the user role.

From this array you could find the array position of "roles" and use it in your module to find the user role.

1
  • Under Development->Execute PHP code, enter: global $user; dpm($user);
    – diamondsea
    Aug 17 '16 at 12:23
1

To be futureproof in case the role name changes it's best to check for the role id (rid) which can be found in the role table in the database.

If you want to check for a role with rid 16, do:

// Load the currently logged in user.
global $user;

// Check if the user has the 'editor' role, when 'editor' has role id 16
if (array_key_exists(16, $user->roles)) {
  // do fancy stuff
}
3
  • 2
    Actually, when you migrate things like roles, machine name will probably be kept, and ID will not
    – Mołot
    Dec 1 '14 at 19:01
  • There is no machine name just a rid and a human name in the role table. The users_roles table assigns a uid to a rid. Dec 2 '14 at 10:54
  • The problem with using rolenames is that it is possible the might change in the future (it is also easy to change their names) and then you will have to go back into your custom code to replace all the names otherwise the things you want to hide or show will not work anymore. If you use the role id you are safe and can change role names without having to check your custom code. Jan 19 at 9:18
1

Above answers did not work, not sure why, I found this blog post and code should be:

global $user;

// Check to see if $user has the administrator role.
if (in_array('administrator', array_values($user->roles))) {
  // Do something.
}

So a helper function could look like this:

/**
 * Check to see if a user has been assigned a certain role.
 *
 * @param $role
 *   The name of the role you're trying to find.
 * @param $user
 *   The user object for the user you're checking; defaults to the current user.
 * @return
 *   TRUE if the user object has the role, FALSE if it does not.
 */
function _user_has_role($role, $user = NULL) {
  if ($user == NULL) {
    global $user;
  }

  if (is_array($user->roles) && in_array($role, array_values($user->roles))) {
    return TRUE;
  }

  return FALSE;
}
1

There's user_has_role() which accepts a role ID. So you could first get a role ID from a role name and then pass that to user_has_role().

$role = user_role_load_by_name('My Role');
$role_id = $role ? $role->rid : NULL;
global $user;
if ($role_id && user_has_role($role_id, $user)) {
  // Yes, this user has this role.
}
0

You can check the role of a user by print_r($user) and in output you will get something like this

stdClass Object
(
    [uid] => 0
    [hostname] => ::1
    [roles] => Array
        (
            [1] => anonymous user // Current user role mine is anonymous in your case it may be different
        )
0

to check if a user has a certain role:

function test_role(){
   global $user;
   if(isset($user->roles['my_role'])){
     return true;
   }
   else {
    return false;
 }
}
0

I modified the top answer here for use with Drupal 8.

<?php
    
use Drupal\Core\Session\AccountInterface;
    
         /**
         * Utility function that checks for single or multiple roles.
         *
         * @param string or array $roles
         *   The role(s) to check.
         *
         * @param AccountInterface $account
         *   The user to check
         *
         * @return bool
         *   Whether the account has the role(s)
         *
         */
        
        function _user_has_roles($roles, AccountInterface $account) {
            // checks if the account has role(s)
            $roles = is_array($roles) ? $roles : [$roles];
            return !!count(array_intersect($roles, array_values($account->getRoles()));
        };

For example:

$isGeek = _user_has_roles(['maker', 'baker'], \Drupal::currentUser());
$isBaker = _user_has_roles('baker', \Drupal::currentUser());
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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