Skip to content

Instantly share code, notes, and snippets.

@yann-yinn
Last active August 29, 2015 14:13
Show Gist options
  • Save yann-yinn/7976b633cb9209a9633e to your computer and use it in GitHub Desktop.
Save yann-yinn/7976b633cb9209a9633e to your computer and use it in GitHub Desktop.
Drupal 7 - check if user has a specific role, checking role id and NOT role labels
/**
* Check if user has one of the roles passed as an array
*
* @param array $roles : array of roles as int (rid stored in database.
* @param int $user_id : optionnal, default to current user if not defined
* @return bool
*/
function user_has_role($roles = array(), $user_id = null) {
if (is_null($user_id)) {
$user_id = $GLOBALS['user']->uid;
}
$user = user_load($user_id);
if ($user->uid == 1) {
return TRUE;
}
$user_roles = array_keys($user->roles);
foreach ($roles as $role) {
if (in_array($role, $user_roles)) {
return TRUE;
}
}
return FALSE;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment