[Drupal] [Drupal 6] How to redirect anonymous users to a Login form on access denied pages?

| | 2 min read

In this article I am going to tell you how to redirect anonymous users to a login form on 403 access denied pages in Drupal. There are some contributed module that provides you this feature but, if you really want to create a custom one for your site just try this. Here I will show you a PHP snippet that redirecting to login page for anonymous users on access denied.

To do this you need to enable PHP filter module in your site.

  1. Create a basic page with Drupal basic page content type.
  2. In block body add the following PHP snippet.

<?php
  global $user;
  if ($user->uid) {
    print "Access Denied: You do not have access to this page.";
  } 
  else {
    drupal_set_message("Access Denied: Please Login");
    $dest = drupal_get_destination();
    drupal_goto('user/login', $dest);
?>
  1. Save your page, now you can get the node id for that page.
  2. Then go to admin/config/system/site-information
  3. In the default 403 (access denied) page settings add the node/id
  4. Save settings. And visit the page as anonymous user. Now you can see a Drupal login page with access denied messages

Please note that the above method should not be attempted on production sites as you are making your site vulnerable to security attacks and you are placing code within the database which makes it difficult to trace and maintain.

This is just an easy way to create a custom access denied login page. If you want you can programmatically create a custom page and use Drupal functionalities. Create a page using hook_menu and write necessary page callback. You can use something like this.


function custom_page_callback() {
  global $user;
  if ($user->uid == 0) {
    menu_set_active_item('user');
    $return = menu_execute_active_handler();
    drupal_set_title(t('Access Denied / User Login'));
    drupal_set_message(t('Access denied.  You may need to login below.'), 'error');
  }
  else {
    drupal_set_title(t('Access Denied'));
    $return = t('You are not authorized to access this page.');
  }
  return $return;
}

Set the menu name as default 403 (access denied) page settings. And that's it you are done with a custom access denied login page!. Logintoboggan module use the same functionality.