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?
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.
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.
In drupal 8 you can get current logged in users info by using currentUser() method.
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.
$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);
You can access to the user roles by just using this PHP snippet:
<?php $GLOBALS['user']->roles; ?>
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With