Redirecting anonymous users to the login page on Access Denied

Last modified: December 7, 2007 - 03:03

This shows how to redirect anonymous users to a sign up/login page when they came across access denied (error 403) pages by using a PHP page. You may also want to check the LoginToboggan module as well for another solution.

Process

  1. Create a node of type page. You must have the PHP input filter enabled.
  2. In the body of the page insert:
    <?php
    global $user;
    if (
    $user->uid) { // this user is already logged in
    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); // this remembers where the user is coming from
    }
    ?>
  3. Submit the node (you should see the "Access Denied: You do not have access to this page." message
  4. Remember this node's ID number
  5. Goto admin/settings
  6. In the section about alternate 403 error pages, insert "node/XXXX" where XXX is your node's ID number
  7. Test it

If you would prefer, you can use this alternate code to force a redirect to the login page after 10 seconds (instead of immediately).

<?php
global $user;
if (
$user->uid) { // this user is already logged in
print "Access Denied: You do not have access to this page.";
} else {
$dest = drupal_get_destination();
$url = "http://www.youdomain.com/user/login?destination=$dest"
drupal_set_html_head('<meta http-equiv="refresh" content="10;URL=' . $url . '">');
}
?>

This didn't work for me

gustav - December 9, 2007 - 19:50

This didn't work for me because it creates an infinite loop of redirects when an anonymous user tries to go to a page like /node/add/blog. Instead I followed http://drupal.org/node/69007#comment-637218

You helped me!!

Justicejayant - June 21, 2008 - 09:03

You helped me, Thanks alot!

This works fine in 5.1.2

phpsharma - November 7, 2008 - 10:22

This worked fine
sharma chelluri

Solution for drupal 5.x

von-p - June 10, 2009 - 14:22

I had troubles to use this code with drupal 5...
Here is the solution I used :

<?php global $user;  if ($user->uid == 0) {
  print
"TO ACCESS THIS PAGE, PLEASE LOG-IN";
 
drupal_get_destination();
 
$block = module_invoke('user', 'block', 'view', 0);
  print
$block['content'];
} else {
  print
"You don't have access to this page";
}
?>

this part is used to print the login block:

  $block = module_invoke('user', 'block', 'view', 0);
  print $block['content'];

-P-

typo

atag - June 24, 2009 - 09:20

There's a missing ";" on:
$url = "http://www.youdomain.com/user/login?destination=$dest"

and $dest already contains the string "destination=" :)

 
 

Drupal is a registered trademark of Dries Buytaert.