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