Checking if a Drupal User has a Role
I'm a little curious why a simple function to check if a user has a role doesn't exist in Drupal yet. Such curiosity that makes me wonder if I've just managed to miss it as long as I've been working with Drupal, so someone feel free to enlighten me. If anyone is looking for the same, please read on...
A fairly common task for me when adding PHP to CCK fields, Views arguments, content templates, etc. is to check whether the current user has been assigned a certain role. Generally in module development you're dealing with permissions and use user_access(), but when you're just customizing a site you often need such role based logic. (Drupal core has some, like the access settings for blocks.)
Use the following simple snippet to check if a user (in this example, it's the logged in user since I'm getting the global $user) has been assigned a certain role on your site:
<?php
global $user;
// Check to see if $user has the administrator role.
if (in_array('administrator', array_values($user->roles))) {
// Do something.
}
?>Replace 'administrator' with whatever role it is you're trying to check against. Alternatively, if you keep a helper module for use on your projects, go ahead and drop this function in it:
<?php
/**
* 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;
}
?>Please let me know if I put a typo up here or you know of an existing or easier way to do this!






Comments
#1 It might be better to add a
Submitted by Guest (not verified) on Thu, 10/25/2007 - 16:06.
It might be better to add a user access permission and then use that instead of just checking if they're part of that role:
<?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!
}
}
?>
The benefit to using this instead is that it isn't targeted to one role. You can have the access permission across a number of different roles. Drupal also already provides a GUI for managing this in admin/user/access.
#2 Well, I understand when
Submitted by Ryan on Thu, 10/25/2007 - 23:21.
Well, I understand when developing a module to use hook_perm() and user_access() to check for permissions level access... but on the fly, when building out a CCK type for example, if I want the available values to differ depending on a user's role, I would use this snippet. I suppose I could use a helper module to define all the special access permissions for a site just as well as I could go through the GUI to create more roles.
Perhaps an answer would be to be a module that lets you create arbitrary permissions and assign those to roles on your site then use user_access() in the CCK/Views custom PHP fields... but then I may as well be checking a user role.
#3 In the long run that becomes
Submitted by greggles (not verified) on Fri, 10/26/2007 - 08:26.
In the long run that becomes quite rigid. Someone changes the role names and you are in trouble - or someone wants to change which roles mean the ability to edit that field and you have to edit code to fix that.
Instead, I tend to use a site specific module (on www.example.com the module would be example.module) where I define a lot of _perms for situations like this and then I use those perms throughout my code.
#4 The more I think about it,
Submitted by Ryan on Fri, 10/26/2007 - 09:39.
The more I think about it, that seems like the right thing to do here. So maybe this post turned out to be more about asking a different question than providing an answer. Thanks for the input, Greg.
#5 thats how i would do
Submitted by moshe weitzman (not verified) on Thu, 10/25/2007 - 17:04.
thats how i would do it.
however, you are usually asking the wrong question if this function is your answer. permissions are far more often checked than inclusion in a role. this function is so specialized that i don't think it needs to be in core.
#6 Agreed... I realized that
Submitted by Ryan on Thu, 10/25/2007 - 23:22.
Agreed... I realized that this isn't something I'd use when creating a module but more when just adding a bit of custom functionality to a node/block's contents or a CCK field/Views argument custom PHP values. Not quite widespread usage.
#7 There
Submitted by Nicholas Thompson (not verified) on Thu, 10/25/2007 - 17:43.
There is...
http://api.drupal.org/api/function/user_access/5
<?php
$u = user_load(array('uid' => 12'));
if (user_access('Administer Nodes', $u)) {
return t('User 12 does have access to this');
}
else {
return t('User 12 does not have access to this');
}
if (user_access('Administer Nodes')) {
return t('Current User does have access to this');
}
else {
return t('Current User does not have access to this);
}
?>
#8 It wouldn't be terribly hard
Submitted by Ken Rickard (not verified) on Fri, 10/26/2007 - 13:42.
It wouldn't be terribly hard to add this to
user_roles().http://api.drupal.org/api/function/user_roles/5
Given the description of the function -- "Retrieve an array of roles matching specified conditions." -- specifying the $user seems a perfectly valid condition, much like user_load() allowing an array of arguments.
I can see some use cases for it -- mostly in theming -- so I'd file a patch for D7.
#9 Hi, it is very useful to
Submitted by Guest (not verified) on Sun, 10/28/2007 - 19:19.
Hi,
it is very useful to point me using the $user-roles array, but it looks like since Drupal 5 the roles array no longer contain the `administrator`? It only contains those roles name we created from admin
#10 You're right... my apologies
Submitted by Ryan on Sun, 10/28/2007 - 21:20.
You're right... my apologies for not pointing it out. The administrator role in the example is just a custom user role I generally use on the sites I create... you can replace that with whatever role you're checking for.
#11 Hi Just a small side note.
Submitted by Alan D. (not verified) on Mon, 02/11/2008 - 20:26.
Hi
Just a small side note. The super administrator has an ID of 1, so a check like this should also be carried out.
// User #1 has all privileges:if ($user->uid == 1) return TRUE;
Otherwise, it may be possible for the primary administrator to be blocked.
Regards
#12 Hey, Thanks guys, you helped
Submitted by Mittal Patel (not verified) on Thu, 10/29/2009 - 22:34.
I wanted to create a block which would be visible on profiles of only certain types of users.
For example, I wanted to show "Subscribe to this employer" block but only when employer's profile was open.
So seeing your code I used the code below :
<?phpif (arg(0) == 'user'){
$user_profile = user_load(array('uid' => arg(1)));
if (in_array('Employer', array_values($user_profile->roles))){
return TRUE;
}
}
else {
return FALSE;
}
?>
and displayed the block only when Employer profile was open.
Thanks for your help guys.
#13 Glad the discussion could
Submitted by Ryan on Thu, 10/29/2009 - 23:48.
Glad the discussion could point you in the right direction!
#14 Checking multiple roles
Submitted by Josh Lind (not verified) on Wed, 12/30/2009 - 21:37.
I often have a few flavors of admins and need to check more than one role.
<?phpglobal $user;
$adminRoles= array('dev','editor','employee');
$adminAble= FALSE;
foreach($adminRoles as $role) {
if( in_array($role, array_values($user->roles)) ) $adminAble= TRUE;
}
if($adminAble) {
print '<p>SHOW THE SPECIAL INFO</p>';
}
?>
#15 array_intersect
Submitted by Capi /. Etheriel (not verified) on Wed, 01/27/2010 - 16:29.
you could further simplify your code with array_intersect:
<?phpglobal $user;
$adminRoles= array('dev','editor','employee');
$check = array_intersect($adminRoles, array_values($user->roles))
$adminAble = empty($check) ? FALSE : TRUE;
?>
#16 Hello! I'm trying to remove a
Submitted by Peter (not verified) on Sun, 02/07/2010 - 12:38.
Hello!
I'm trying to remove a user role after the submission of a webform, now that I've checked that the user has the specific role, how can I remove it? I've searched everywhere but I can't find something similar.
#17 Removing a role from a user
Submitted by Tom Van Schoor (not verified) on Fri, 02/12/2010 - 06:35.
That should be prety easy with a little sql...
<?php
$sql = "DELETE FROM {users_roles} WHERE uid = %d AND rid = %d";
db_query($sql, $user->uid, $role_id);
?>
Or if you only know the role name and you want to do it in one query:
<?php
$sql = "DELETE FROM {users_roles} WHERE uid = %d AND rid = ("
." SELECT rid FROM {role} WHERE name = '%s' "
.")";
db_query($sql, $user->uid, $role_name);
?>