Community & Support

Given a user's uid, how to check its role?

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

Thanks,

Comments

<?phpglobal $user;if

<?php
global $user;

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

Iam not much of an author so i'll just...

user_load

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"

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

For a node it will work like this

<?php
$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:

<?php
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

I see my answer was givin' a

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.

Iam not much of an author so i'll just...

*_*

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

check permissions, not roles

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

Can I use the following code

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

*_*

You should use in_array() of php.

Regards.

:)
Beautifulmind

Can you please give me the

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

*_*

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

:)
Beautifulmind

nobody click here