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
- Create a node of type page. You must have the PHP input filter enabled.
- 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
}
?> - Submit the node (you should see the "Access Denied: You do not have access to this page." message
- Remember this node's ID number
- Goto admin/settings
- In the section about alternate 403 error pages, insert "node/XXXX" where XXX is your node's ID number
- 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
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
infinite loop fixed here:
http://drupal.org/node/69007#comment-637218
or here:
http://drupal.org/node/59861
You helped me!!
You helped me, Thanks alot!