I'm having the darndest time figuring this out. Here's the scenario I want:

#1 When user 1 logs in, redirect to /admin

#2 When any other user logs in from a LoginToboggan 404-generated login form, redirect to the page the user wanted (this should also work for a User module login block)

#3 When any other user logs in at /user, redirect to <front>

Here's my code for URL destination:

global $user;
if ($user->uid == 1){
   return 'admin';
}
elseif ({some item here} != 'user') {
   return {some item here};
}
else {
   return '<front>';
}

For {some item here} I've tried $_GET['q'] and $_SESSION['login_page']; they always return "login_redirect." I finally stumbled upon $_REQUEST['destination'], which gives me the path I want, but I've not yet figured out how to save that in the Redirect condition and use it again in the URL destination. I've tried variable_set() as described here, but I'm not getting it right.

So, #1 and #3 work just fine, but #2 doesn't.

Any suggestions?

Comments

geshan’s picture

I also need to do it but am not getting how to do it. :-(.

akolahi’s picture

I am also looking to get my users to be redirected to the page they logged in from. In another forum i found this

?php
global $user;
if ($user->uid) {
  $text = "Log Out " . $user->name;
  $path = "logout";
} else {
  $text = "Log In";
  $path = "user";
}
print l($text, $path, array(), drupal_get_destination());
?>

utilizing the drupal_get_destination() function. I tried to utilize that in the PHP snippet of Login Destination but got nowhere.

Any ideas on the code needed to insert Login Destination to get users to return to their original page after loggin in? As a side note I think it would be most ideal to have a checkbox to have administrators just select this option as part of this module since this seems to be a frequently requested function.

thanks.

krempe’s picture

Same problem. I simply want to do what drupal.org does when I log in: It redirects me to the page I come from.
I tried to use the module login_destination. It works fine with static nodes like 'node/123', but

return $_SESSION['login_page'];

as a PHP-snippet doesn't work.

Any idea?

thanks.

ardas’s picture

Guys, if you want to do what drupal.org does when I log in simply disable login_destination.module

geshan’s picture

HOw do you do it?

katherined’s picture

What is the correct use of $_SESSION['login_page'] ?

Assuming you do not have a login block on the originating page, and you click a link to get to user/login? How do you send the user back to the referring page?

Thanks.

mrtoner’s picture

@ARDAS: If you'll go back to my very first post, you'll see why disabling Login Destination isn't an option. Even for someone, perhaps krempe, that wants to duplicate the functionality seen on d.o, that can only be achieved by enabling the Login block, which many users don't want.

For the rest of you who have been looking for this, well, I figured it out. Put this into your Login Destination URL field:

global $user;
if ($user->uid == 1) {
   return 'admin';
}
elseif (substr($_SESSION['login_redirect'],0,4) != 'user') {
   return $_SESSION['login_redirect'];
}
else {
   return '<front>';
}

and put this into the Redirect condition field:

if ($_REQUEST['destination'] != 'login_redirect') {
    $_SESSION['login_redirect'] = $_REQUEST['destination'] != '' ? $_REQUEST['destination'] : $_SESSION['login_page'];
}
return TRUE;

These are both PHP snippets, of course. The <front> in return '<front>' can be changed to whatever path you like for users that login by using a user/* link.

Rob T’s picture

The code in #7 works well for me so far in my 6.3.

Grimlock’s picture

@mrtoner or anyone

Thanks for getting this to work with LoginToboggan. I was also wondering if you could provide the conditional PHP code for users who register from the LoginToboggan 404 page to be returned to the original page they logged in from instead of being taken to their user profile page. This happens because the user clicks "Create new account" and once they log in it takes them back to the user/register node.

Thank you,

Grim

fgasking’s picture

Thanks mrtoner for that snippet!... Working a treat!

One quick question - but with the part:

else {
   return '<front>';
}

I have a "log in" link in my site header, which takes the user from the page they were on to "/user/login" to log in. How can I adapt the above so that instead of just directing the logged in user to the front page, it directs the user back to the page they clicked the "log in" link from?

mrtoner’s picture

@fgasking: $_SESSION['login_redirect'] has the value of $_REQUEST['destination'] before LoginToboggan wiped it out, so

return $_SESSION['login_redirect'];

will send the user to that page.

fgasking’s picture

Thanks mrtoner! - although i've now replaced "return ''" with the above change - , if i'm on /about-us and click a link on that page to /user/login to then log-in - it redirects me logged in to the home page, rather than back to /about-us

Do I maybe need to also update the redirect condition aswell?

mrtoner’s picture

Something else is working against you, it appears. There's nothing in the destination URL snippet I posted above except for return '<front>'; that will redirect to the home page. The condition doesn't need to be updated: it will always return TRUE.

What's your complete snippet look like?

fgasking’s picture

Version: 5.x-1.x-dev » 6.x-2.1

I've got this under URL:

global $user;
if ($user->uid == 1) {
   return 'admin';
}
elseif (substr($_SESSION['login_redirect'],0,4) != 'user') {
   return $_SESSION['login_redirect'];
}
else {
   return $_SESSION['login_redirect'];
}

..and this in Redirect condition

if ($_REQUEST['destination'] != 'login_redirect') {
    $_SESSION['login_redirect'] = $_REQUEST['destination'] != '' ? $_REQUEST['destination'] : $_SESSION['login_page'];
}
return TRUE;

I am guessing I don't actually need the first else if, but even if I take that out it makes no difference. Still redirected to the front page.

mrtoner’s picture

Version: 6.x-2.1 » 5.x-1.x-dev

Um, I'm thinking that $_SESSION['login_page'] doesn't exist in the D5 version, based on the description for this project. Try $_GET['q'] or $_REQUEST['q'] instead. This was a D5 support request, originally.

fgasking’s picture

Version: 5.x-1.x-dev » 6.x-2.1

Sorry, I was using Drupal 6, but the above still redirected to the home page.

However, I have found a suitable solution by overriding the "Log in" link and tagging on drupal_get_destination() when it is built for the page. That way the login form knows where to direct the user to once logged in, the Logindestination code from above will still override and redirect the user to the resource they were trying to access and also the added bonus was that I also the above worked for "log out", so the log out directs you to the page you were on, and not home :)

Thanks for your help on this though, i'm glad to have finally got it sorted and your solution helped a lot with the 403 errors!

Flying Drupalist’s picture

Hi, I have the login form printed in a block like this: print drupal_get_form('user_login');

Whenever I login with that, I am redirected to the user's profile page. The 404 login form works fine, but my custom login doesn't. Any help with that?

I'm on d6.6

indianroo’s picture

Just to add my two cents: I found that the setting $_SERVER['HTTP_REFERER'] had the URL of the previous page
and returning that had the effect of going back to the page where the user clicked login after they had logged in. You probably have to do some sanity checks to check the URL is not an external one, etc.

lwiegand’s picture

fgasking #16 Can you provide the code you used for this (your solution from #16)? Thanks.

fgasking’s picture

Apologies for the long delay - been a while since i've logged on!

I overrode the Log in link by using the menu_item_link hook (http://api.drupal.org/api/function/theme_menu_item_link/6) and picking up the "Log in" link and appending the destination. However I did some quick filters to ensure that destination was not the user login/registration pages. This follows on with the Logindestination settings previously mentioned.

It's very messy (and a while since I did it) and is stored in the theme's template.php file at present - but at the time it was done quickly due to tight deadlines and some of this should get moved out into custom modules in hindsight - as well as get tidied up significantly. Hope this is useful still though as a starting point.

The rest of the surrounding code should be for the rest of the function to continue as intended.

function yourtheme_menu_item_link($link) {

	  if (empty($link['localized_options'])) {
		$link['localized_options'] = array();
	  }

	  $options = $link['localized_options'];

	  // Merge in defaults.
         $options += array(
           'attributes' => array(),
           'html' => FALSE,
         );

         //Override the log in and log out link 
         if ($link['title'] == "Log in"){

		if (drupal_get_destination() == "destination=user%2Fregister" || drupal_get_destination() == "destination=user%2Flogin" || drupal_get_destination() == "destination=user"){
			$destination = "destination=node";
		} else {
			$destination = drupal_get_destination();
		}

		return l(t('Log in'), 'user', array( 'query' => $destination, 'alias' => FALSE ));

         } elseif ($link['title'] == "Log out"){

		return l(t('Log out'), 'logout');	

         } else {

		return '<a href="'.check_url(url($link['href'])).'"'. drupal_attributes($options['attributes']) .'><span>'. ($html ? $link['title'] : check_plain($link['title'])) .'</span></a>';	
  
         }
}
sbydrupal’s picture

I am trying to create a Menu Link "Log in" that will link to /user/login and redirect to original url once user logged in.

#20 and #14 above by fgasking should be the answer, however, does not seem to work.

I have placed #20 in template.php and placed #14 in related boxes in Login Destination module.

Would #20 and #14 work for this case, or am I misunderstanding something about the goal of the postings?

Thanks for any feedback

aac’s picture

I am using Drupal6 with login destination and login toboggan modules. I have created a page content type with php mode. On this page i have used the following code to show the login block.

 global $user;
  $destination = drupal_get_destination();
  print $destination;

 if ($user->uid == 0)
  {print drupal_get_form('user_login');}

Now i would like that if a user logs in from this page, then he should remain on the same page after logging in. So he will now be able to see the links (which are meant to be visible to authenticated users only) to submit some custom content type.

I have used the following code in login destination module URL section (php snippet)-

global $user;
if ($user->uid == 0)
 {
   if ($destination == 'node%2F24')
    {return './node/24';}
 }

And nothing in Redirect condition.
But it is not working, it redirects to the user page after logging in.
Thanks for any help!!!

Anonymous’s picture

I have tried two things:
1- copying the PHP snippets from #7 above and adapting them for the use I want

2- disabling Login Destination, in hopes that it would work the way D.O does

Neither of these worked for me - users are still directed to the User Profile page. I want them to be directed either to the page or to the page they were trying to get to when they got the login prompt.

Please help!

pribeh’s picture

I'm using Drupal 5 and none of the snippets above have worked for me. I even tried amending #14 with #15's suggestion. The user will always be redirected to the front page. Has anybody solved this for Drupal 5? I'm simply trying to redirect users to the page they left after clicking on the user/login link within my primary menu. Design-wise I do not have the option of using the block and I am also using LoginToboggan.

IbnDrupal’s picture

Used the module it didn't work.

Had to resort to the following in D6.

Add the code to your template.php file.

Make sure you change mytheme to your theme name.
Also this searches for "Log In" link in the menu, if you have called it something else please also amend that too.

function mytheme_menu_item_link($link) {
  if ($link['title']=='Log In') {
    if (empty($link['localized_options'])) {
      $link['localized_options'] = array();
    }
  
    //set the destination, for different destinations for different users, work it out here
    $destination = drupal_get_destination();

    // Merge in the query with current localized options
    $link['localized_options'] += array(
      'query' => $destination,
    );
  } 
  return l($link['title'], $link['href'], $link['localized_options']);
}  

jboeger’s picture

subscribing.

techypaul’s picture

subscribing, sometimes drupal makes things harder than it should :) lol.

burgs’s picture

This is working for me in drupal 6

if (substr($_REQUEST['q'],0,4) != 'user' && $_REQUEST['q'] != '') {
   return $_REQUEST['q'];
}
else {
   return '<front>';
}

This does a redirect back to the original page, unless it was like user*

One thing to be careful with all this logging in and out to test - my php destination code wasn't being saved. For some reason, it was losing my latest updates to the code. Always go to /admin/user/login_destination afresh after you've saved the form just to double check.

tallsimon’s picture

thank you for these.
the snippets above (#28, #7), work to redirect to the page you logged in from, mostly. but if you use customerror for your 403 page, it redirects to /customerror/403 rather than the page the user was trying to access!

Is there any code which can capture the page they were trying to see (i.e. in the address bar), despite customerror being enabled for these pages? I would like to do this:

If front page - standard user logs in -> redirect to 'groups'
If front page - admin logs in -> redirect to 'admin'
If any other page (including forbidden/403 error) - ANY user logs in -> redirect to page they were trying to access

would be very grateful for any help with this!

tallsimon’s picture

I wonder if the email registration module which generates my sign in form is modifying the $_request variable... Why else does it persistantly forward me to the user profile if I use this variable or front page if I use th arguement telling it not to redirect if the variable is 'user'...

Edit ...

this was indeed part of the problem, now at least the function to return to the login page works!

Als’s picture

I am posting this here following pribeh's comment (#24).
For anyone using Drupal 5, sending users back to where they came from after login can be done via a workaround. Technically it is not the same, but does the job and is pretty standard in terms of usability.
- Install Logintoboggan, enable login form on "access denied" pages.
- Create a node with title "Login" and a very short body: "You have successfully logged in" + "Go back".
- Link "Go back" to a Javascript "back" call, i. e. javascript:history.back(). You can make it as a button instead of text.
- Install Login Destination, redirect user to a custom fixed URL after login. Fixed URL is that of the new node.

When trying to see reserved pages, users will see the "access denied" message and the login function. They will login and see the confirmation message. Clicking "go back" they will be brought one step above in browser history, which is exactly the "page that they come from". Now that they are logged in, the page content will show up and they will get the feeling that site remembers the previous location.

tfleming’s picture

okay, not being a Drupal developer (our org hired a firm to create our site, but we're having to learn fast how to correct problems with it), I need some very low-tech-jargon assistance.

This is the code we now how in the URL Destination Settings box:

global $user;
$nid = db_result(db_query("SELECT nid FROM {node} WHERE type = 'user_profile' AND uid = %d", $user->uid));
if ($nid == null) {
return 'user/' . $user->uid .'/edit/user_profile';
}
else{
return 'node/' . $nid;
}

There is no code listed in the Redirection Condition Settings (the radio button for "Always" is checked).

What I need is what seems to be being described above. I've copied and pasted the code from #7 above, but there appears to be no change at all. I'm getting the same result as before. Perhaps something in the set-up (as defined in the code we have now for this) is overriding any change to the code?

Again, please low-tech. I don't know how to turn off Login Destination or change/update/upload modules. Copy-and-paste is about all the functionality I have, I think.

Thanks,
Tony

rsvelko’s picture

Status: Active » Postponed
betancourt’s picture

There are two modules that have this functionality:
http://drupal.org/project/logintoboggan
http://drupal.org/project/r4032login

Cheers

beyond67’s picture

Im surprised this hasnt been corrected yet.

Here is what im trying to do:

1) If I login via /user page, I want Login Destination module to redirect to specified page found in its settings.
2) If I login from an access denied page (LoginToboggan redirect), I want to redirect to that denied page not what was specified in number 1 above.

brpubs’s picture

subscribing

gamepaused’s picture

This is how I did it - with some of the code on here, and then print l

On my login button -

print l(t('Log In'), 'user/login', array('query' => drupal_get_destination()));

Redirect code -

global $user;
if ($user->uid == 1) {
return 'admin';
}
elseif (substr($_SESSION['login_redirect'],0,4) != 'user') {
return $_SESSION['login_redirect'];
}
else {
return $_SESSION['login_redirect'];
}

Page code -

if ($_REQUEST['destination'] != 'login_redirect') {
$_SESSION['login_redirect'] = $_REQUEST['destination'] != '' ? $_REQUEST['destination'] : $_SESSION['login_page'];
}
return TRUE;

Seems to be working great.
If you try logging in on say, user/register - it takes you to the user/edit page instead ;)

bobmct’s picture

Can you tell me exactly where you placed the code shown in your example in the Drupal 6.22 code base? I've been struggling with the same need (to have the user redirected back to the originating page).

Thanks

waltercat’s picture

Bumping this again, I am not sure what I am missing. If I have redirection settings to "Always" and Destination URL Settings to "Return user to where he/she came from. (Preserve destination)" Shouldn't this keep my user on the same page? I am running D6 and I have loggintobogin as well. Can anyone suggest what I am doing wrong? I have tried every combination above and none work. Thanks!