I've got 2 roles on my system -uzman and isveren- and several views that need to be restricted to either uzman or isveren. For that purpose, I have been trying to check access control with PHP. I can't use role based access check because then administrator would see all because he has access to all views. Anyway, I am using

if (in_array("uzman", $account->roles)) {
return TRUE;

which works, but I see many undefined offset:4 messages in dblog (4 is uzman's rid). What is the correct way to check access with PHP in Views module?

  • 1
    Views already has plugins to check role and permissions. Why do you need to use raw PHP to do the same? – AyeshK Jan 16 '15 at 13:48
  • I can't check role-based access, because then the administrator would have access to them by menu as well. – Kartagis Jan 16 '15 at 14:15

The correct way is to create a custom module and implement hook_permission() to define an appropriate permission:

function hook_permission() {
  return array(
    'administer my module' => array(
      'title' => t('Administer my module'),
      'description' => t('Perform administration tasks for my module.'),

Grant that permission to the roles that require access to it, and then use user_access() to make the access decision:

if (user_access('administer my module', $account)) {

As AyeshK points out in the comments, you don't actually need the second part - Views has n plugin for access based permissions already, which you can configure through the UI. So once you've added the permission and granted it to the relevant role(s), it'll be easy to get what you're looking for.

  • Okay, I can do that; but how would I let users access the view within the if block? – Kartagis Jan 16 '15 at 13:46
  • Sorry I'm not following - the second code block above is what you use to determine access. Though you don't need to in the case of views, answer updated – Clive Jan 16 '15 at 13:49
  • I have to use PHP to determine access, because if I check by role administrator would have access to the view's menu as well, which is not what I want. – Kartagis Jan 16 '15 at 14:19
  • I was just answering your question: What is the correct way to check access with PHP? (I actually missed the bit about the user 1 account first time round, apologies). Either way, if you don't want/can't use the correct way, then basically whatever works for your use case is the "correct way". Drupal doesn't have a "user access including the user 1 account" function, as the user 1 account is SU. It not having access to something could/should be considered a bug – Clive Jan 16 '15 at 14:32
  • Sorry, I should have been clearer with my question. Let me update it. – Kartagis Jan 16 '15 at 15:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.