How to get the currently logged in user's role in Drupal 7?
Asked Answered
M

4

18

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?

Magdalenmagdalena answered 8/3, 2011 at 12:34 Comment(0)
M
26

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

<?php $GLOBALS['user']->roles; ?>
Monotony answered 8/3, 2011 at 12:42 Comment(0)
S
27

$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);
Solmization answered 10/3, 2011 at 22:35 Comment(1)
On the second 'arrayed' needle snippit, per the docs 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() would do the trick for that though.Stele
M
26

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

<?php $GLOBALS['user']->roles; ?>
Monotony answered 8/3, 2011 at 12:42 Comment(0)
M
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
}
Magdalenmagdalena answered 9/3, 2011 at 6:19 Comment(0)
T
2

// 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;
    }
Tarim answered 11/5, 2015 at 9:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.