Take the 2-minute tour ×
Drupal Answers is a question and answer site for Drupal developers and administrators. It's 100% free, no registration required.

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

I found this but it is for Drupal 6.

share|improve this question

4 Answers 4

up vote 45 down vote accepted

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
}
share|improve this answer
    
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
3  
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. –  marcvangend May 15 '13 at 18:47

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
}
share|improve this answer

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.

share|improve this answer

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
        )
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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