0

I have a section of my drupal website that I only want displayed to users that are logged in. So if they click on "My Page" link and the user is not logged in it should redirect them to a login screen. I have attempted to complete this task by using the following code.

<?php
if (!user_is_logged_in()) drupal_goto('user/login'); ?>

This doesn't seem to throw any coding errors but none of my links such as register, login etc work. I get an error that I have a redirect loop that will never complete. I cannot seem to find a good solution for completing this.

  • How you are building the link? If you are building the link using drupal menu system, then you can use the module - drupal.org/project/menu_access . It will help you. – Parvind Oct 1 '14 at 13:05
  • I'm not sure what you mean by how I'm building the link. Can you be more elaborate so I can answer your question to the best of my knowledge. On a site note, for all of the pages that require user login access I have them set up as custom content types. – user3262111 Oct 1 '14 at 13:25
  • 1. Install this module - drupal.org/project/menu_access 2. Go to the example.com/admin/structure/menu, edit your menu link, check the proper roles for the menu item under "Visibility setting". – Parvind Oct 1 '14 at 13:35
  • Will this plugin work for Drupal 7? – user3262111 Oct 1 '14 at 13:52
1

If you write down this piece of code outside any hook or function, it is normal that it loops because the user is always "not logged in".

However, if you've created your "page" through the admin menu system, as Parvind said, you can use Menu Access module or use that piece of code:

function hook_node_view($node, $view_mode) {
  if($node->nid == 'yournodeid" && $view_mode == 'full') {
    if (!user_is_logged_in()) 
      drupal_goto('user/login');
  }
}

If you've created the node programmatically (hook_menu()), you can use access argument like this:

$items['testpage'] = array(
  'title' => 'Authenticated users',
  'page callback' => 'test_func',
  'description' => 'This page is accessible to authenticated users only',
  'access callback' => 'user_is_logged_in',
  'type' => MENU_CALLBACK,
);
  • Where do I place this code? – user3262111 Oct 1 '14 at 13:27
  • Are you new to Drupal? How did you create your page that you want to be accessible for authenticated users only? – Djouuuuh Oct 1 '14 at 13:36
  • I created the page through the admin system. – user3262111 Oct 1 '14 at 13:50
  • Maybe you could have a look at this module: drupal.org/project/menu_item_visibility and see if it redirects anonymous users too. – Djouuuuh Oct 1 '14 at 14:01

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.