Redirecting anonymous users to the login page on Access Denied

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!

 
 

Drupal is a registered trademark of Dries Buytaert.