Web Design, SEO and Web Applications Development

Checking if a user has a given role in D6

Drupal's API doesn't contain any ready-made function to check if a user has a certain role. While it's certainly easy enough to do, it can take a moment to figure out initially. Here's a little function that demonstrates how to do it. It isn't itself particularly useful since checking for roles is trivial without it, but it should serve as a point of demonstration.

<?php
/**
* Function to determine is a given user has a role.
*
* @param $role
*  A string containing the role we want to check.
* @param $uid
*  The UID of the user we wish to examine for the role. If not provided,
*  the currently logged in user will be user.
* @return
*  TRUE if the user has the role. FALSE otherwise.
*/
function <modulename>_user_has_role($role, $uid = FALSE) {
 
// Can't just check for !$uid since UID 0 is the anonymous user.
 
if ($uid === FALSE) {
    global
$user;
  }
  else {
   
$user = user_load($uid);
  }
 
 
// Check for the role.
 
if (in_array($role, $user->roles)) {
   
// Role found
   
return TRUE;
  }
 
// Role not found.
 
return FALSE;
}
?>

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.

More information about formatting options