views:

113

answers:

2

how can I know in Drupal if the role of the logged-in user ?

In the $user variable there is not role information.. I need to specify specific php code depending on the user role in my custom module.

N.B. In $user there is a field 'role' but it always contains "authenticated user". What I need to know is the specific role (I've created in advance) of an authenticated user.. i.e. 'forum administrator', 'normal user'.

thanks

+2  A: 

It's better to check for an access instead of checking for a role, since role names can be changed in the admin interface, thus breaking your code. You could in your module define a permission, "has role X".

If you really want to check a users roles, that is possible. {The users_roles} table is a join table between users and roles. So you can use it to get all the rid (role ids) of all the roles a user have. You can lookup the name in the role table. Sample code:

global $user;
$query = db_query("SELECT r.name FROM {role} AS r
                   LEFT JOIN {users_roles} AS U on r.rid = u.rid
                   WHERE u.uid = %d", $user->uid);
while ($name = db_result($query)) {
   // check the role names...
}
googletorp
mhm, but if I need to assign a specific code to a specific role, how can I refer to it without mentioning the role name ?
Patrick
Use the role id.
Finbarr
@Patrick, like I said, best option is to create a permission and check for that, since that is code safe, since permission names can't be changed through an interface, role id and role name can.
googletorp
There is actually a case where checking the user role instead of the permissions make sense. A WYSWYG editor that assigns different toolbars to different roles, normally checks the roles assigned to a user; it doesn't create a permission for each of the toolbar created (it would not help when a toolbar is assigned to different roles, but only one toolbar can appear for each user).
kiamlaluno
+1  A: 

You actually don't need to do your own db_query(): user_load() already does this. $user->roles is an array; just do:

if (in_array('role to check', $user->roles)) { 
  // ...
}
Mark Trapp
In the global variable `$user`, the property `$user->roles` is already populated. If you are looking for the roles of the currently logged in user, you can use that global variable.
kiamlaluno

related questions