1
votes

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

2 Answers

4
votes

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)) { 
  // ...
}
2
votes

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...
}