I know the user's uid, how to check its role?

Thanks,

Comments

Iumentum’s picture

global $user;

if ($user->role[2]) {
  echo "authenticated user";
}

designwork’s picture

Hi Iumentum,

Wich Drupal do you have installed? I give you a short intro in Drupal 5.x. You load the user object via the user_load.

Lets suppose you want the role of the user on his user account.

first you make a user.-profile.tpl.php there are some examples around how to do this.

load the user via the first argument "user/uid"

 $useruid = arg(1);
$accountowner = user_load(array('uid'=>$useruid));
print t('User-role: ');
print $accountowner->roles;

For a node it will work like this

 $node_owner = user_load(array('uid'=>$node->uid));  
 print t('Nodeowner: ');
print $node_owner->roles; 

Print only if a user has a certain role:

get the id´s of the rolles via print_r($node_owner->roles);

Now you can start:

 if ($node_owner->roles[2]) {
    print t('authenticated user');
} else { 

print l('login to become a Member', 'user/login')

}

So i hope this will help you.

Cheers from Cologne

Dirk

Iumentum’s picture

I see my answer was givin' a bit to fast and didnt think he was asking for a specific user loaded by uid :)
But just wanted to point out that the roles exists within the user object.

beautifulmind’s picture

Whether you assign a user any role or not, there is a role always assigned for a registered user.
Use the following code to check what's the role of a user possessed?

print_R($user->roles);

Yes, $user->roles is an array.
Now, when you get a clear idea of roles, just compare those roles in your code!
:)
Beautifulmind

Regards.
🪷 Beautifulmind

marcvangend’s picture

I don't know what you want to achieve by checking the role, but in most cases, it makes more sense to check a permission than to check a role.

<?php
if (user_access('search content')) {
  // code for users with this permission
}
?>
navs’s picture

Can I use the following code to show an audio player?

<?php
global $user;

if ($user->role[4]) {
  echo "I'll show the player now";
}
?>

On my site, I have unregistered users, and three other user roles that have different permissions each. I want only roles 2 & 4 to be able to access this audio player. Can I do this in a safe manner that it will always work?
Thanks
Navs

beautifulmind’s picture

You should use in_array() of php.

Regards.

:)
Beautifulmind

Regards.
🪷 Beautifulmind

navs’s picture

Can you please give me the syntax for using in_array(). I don't know if this is correct, please let me know:

<?php
if (in_array("trader", $user->role)) {
    echo "Is a trader";
}
?>

Let me know if the syntax is correct for checking if a user with role "trader" is logged in?
Thanks
Navs

beautifulmind’s picture

Yes it is.
But I think its $user->roles and not $user->role
Check it.

:)
Beautifulmind

Regards.
🪷 Beautifulmind