4.4. Checking Permission: user_access and Friends

Now that you've created a permission, how do you actually make sure that it is respected in different actions? The major function is user_access(), and it can be called with just one parameter, as in this simple example:

if (user_access('some permission')) {
  // Code that should only run if the current user has "some permission"
}

The function checks to see if the current user has that permission and returns either TRUE if he does or FALSE if he does not have the permission. In this first example, it is called with just one parameter: the name of the permission to check. It's also possible to call it for a specific user to see if that user has access to do something. An example of this second variation on user_access() can be seen in the function user_access:

if (user_access('administer nodes', $account)) {
    return TRUE;
  }

In this case, the user account identified for the node_access function is tested to see if it has the permission "administer nodes," because that permission grants a user access to all content on a site.

A third very common example of using user_access comes from the hook_menu definition.

4.4.1. Menu Callback Permissions

One of the most common places to check a user's access is in the menu definition. Drupal's menu system is based on each module implementing the hook_menu function, which returns an array filled with information about the menus and paths defined by that module. The array has two keys that are related ...

Get Cracking Drupal®: A Drop in the Bucket now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.