Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the currently logged in user's role in Drupal 7?

How to get the currently logged in user's role in Drupal 7 ? Do you know a simple way of accomplish this ? Is there some drupal core functions for this?

like image 867
radu c Avatar asked Mar 08 '11 12:03

radu c


People also ask

How do I get user roles in Drupal 9?

In the Manage administrative menu, navigate to People > Roles (admin/people/roles). You will find default roles Anonymous user, Authenticated user, and Administrator already present. Click Add Role to add a custom role.

Is user logged in Drupal?

The function to use is called user_is_logged_in , and it can determine if a given user is logged in. For complete documentation on the function, click the appropriate link from the following, based on your Drupal version: Drupal 7 user_is_logged_in function information from drupal.org.

How do I get current users in Drupal 8?

In drupal 8 you can get current logged in users info by using currentUser() method.

How do I find my current user id in Drupal 9?

Once you have the user id, you can use the User::load to get the user object. $user = User::load(\Drupal::currentUser()->id()); Here is an example of retrieving specific information from the user object.


3 Answers

$user->roles is an array of the roles that belong to the user keyed by the role ID, value is the role string. So if you wanted to check if user had role 'authenticated user' your code snippet would look something like this (not necessarily the most optimized approach, in_array is a fairly performance-expensive function):

global $user;

if (in_array('authenticated user', $user->roles)) {
     //do stuff here
}

Note that in_array can also accept an array as the "needle" (argument #1) so you could check against multiple role options:

in_array(array('authenticated user', 'anonymous user'), $user->roles);
like image 110
mattacular Avatar answered Oct 01 '22 01:10

mattacular


You can access to the user roles by just using this PHP snippet:

<?php $GLOBALS['user']->roles; ?>
like image 22
Artusamak Avatar answered Oct 01 '22 02:10

Artusamak


I have found a interesting solution to check for multiple roles of a user:

global $user;
$check = array_intersect(array('moderator', 'administrator'), array_values($user->roles));
if (empty($check) ? FALSE : TRUE) {
    // is admin
} else {
    // is not admin
}
like image 24
radu c Avatar answered Oct 01 '22 01:10

radu c