I'm trying to get the module login destination to redirect to the previous viewed page. I've searched far and wide without success.

For the drupal 7 version of the module there is no setting to automatically redirect to the previous page, and I'm unsure what php to place in the Experts Box.

I'm trying to redirect from this page:
user/login

The site is https if that matters. Hopefully I just overlooked something obvious.

Comments

Sagar Ramgade’s picture

Hi,

You need to use drupal_get_destination to redirect to the previous page, check http://api.drupal.org/api/drupal/includes!common.inc/function/drupal_get... for more info.

Acquia certified Developer, Back end and Front specialist
Need help? Please use my contact form

pszpak’s picture

In this case I am still unsure how to proceed and actually need some hand holding (or a point to a php snippet);

Login Destination says:

If the PHP option is chosen, enter PHP code between . It should return either a string value or an array of params that the url($path = '', array $options = array()) function will understand, e.g. return array('blog', array('fragment' => 'overlay=admin/config', ), );

But my weak attempt doesn't seem to do anything:


$destination = drupal_get_destination();
print $destination;

It should output a string that login destination can use? But nothing happens.

Can I use drupal_get_destination in this php box without including it on the used to get to the log in page? Or is this url always available to be called upon?

Sagar Ramgade’s picture

Try this :

<?php
return drupal_get_destination();
?>

Acquia certified Developer, Back end and Front specialist
Need help? Please use my contact form

pszpak’s picture

Thanks for your reply.

At least something happens, although it is an error message:

Notice: Undefined offset: 0 in login_destination_drupal_goto_alter() (line 292 of /var/www/webapps/drupal-7.12/sites/all/modules/login_destination/login_destination.module).

LoMo’s picture

You might, instead, want to try the LoginToboggan module, which does (pretty simply and without any need to add PHP) provide this functionality. Indeed, you can have the login form on every page (no redirection when submitting the form), or (if your login form is Captcha-protected, for example) you can set it to provide just the simple link normally provided by Drupal, but return you to the referring page (the original page they were on before clicking on the link — i.e., what you want).

It has a number of other nice options so I definitely recommend trying it out.

Okay, I hadn't tried the Login Destination module before, so I've also just installed it to see if I can replicate your issue. Some observations:
In order for it to work, the setting (on admin/config/people/login-destination/settings) called "Preserve the destination parameter" must be UNchecked (otherwise it overloads any rules created by this module). Take a look at that.
I don't see the PHP/"expert" mode directions, hmmm... Oh, now I see: You need to enable the PHP Filter to be able to use them, of course. That said, an empty call to drupal_get_destination() would best be made by a custom module that provides the login link, otherwise if it's only added on the login page, you would just stay on /user after logging in. I don't think that's what you want. I think there must be a way to get the "referrer" and use it as a redirect parameter, but really, unless you have other reasons to use this particular module, I'd strongly suggest just trying LoginToboggan.

Hope that helps. :-)

See you at the Drupalcon!

pszpak’s picture

Solved it!

LoMo I tried your solution but with no dice initially, but the different google searches and reading about logintobbagon (LTB) managed to provide the pieces of the puzzle that I was missing.

I'll lay them out here in detail in case other people are wondering how to do this (and I can see how this would be a commonly sought feature after login).

I used logindestination (LD) module in the end, I couldn't get it to work with LTB, but I'm sure you can.

The key is getting this :
drupal_get_destination
from the page that you are linking from. So if I'm on the products page and linking to the login page I have to include it on the login link. In my case I have the link in a block. Before I didn't include drupal_get_destination in the link, but now I do. This is how I generate the link in my block:

 global $user;
    if ($user->uid == 0){
        print l("Login","user/login",array('query' => drupal_get_destination()));
        }
    else{
    print l("Logout","user/logout",array('query' => drupal_get_destination()));
} 

This is the critical part I was missing

I'm learning php, so I can't clearly explain it, but what I do know is that this tells drupal to get the current page and remember it (more or less).

Then I go to the LD modules configuration and create this rule for login and logout in the Expert field:

$destination = drupal_get_destination();
print $destination;

Since drupal_get_destination is now available it can be output as a string that LD can use to bounce the user back to the page just viewed, which is awesome. Thanks for the help everyone on this thread.

LoMo’s picture

Glad you got that sorted out. That was what I was seeing, too... that you need the drupal_get_destination() call to happen before you go to the login page; and the "login destination" module doesn't seem to do that. I'm not sure why you had problems with the logintoboggan module for this; as far as I can tell, this should be default behavior for login links provided by that module (though I've usually used it to provide a nice "login block" that opens up (changes from link to block in one of the sidebars) when clicked—in that case, it also submits the login form and stays on the page (but of course you can't cache the page if the login form includes any Captcha, etc, which is why you might want the login link that redirects back to the "referring" page.

Anyway, your solution looks sound. I think it should also work just with a "PHP filter" block and no module. I don't think that, for your requirement, you need the LD module at all.

See you at the Drupalcon!

Danny Englander’s picture

Thanks, This worked really well, just what i was looking for. I found I did not need the Login destination module though.

thoughtcat’s picture

Thanks very much for posting that code! Here is my variation on it. I'm using it on my access denied page:

<?php
global $user;
    if ($user->uid == 0){
echo "Access Denied! To access this content, you probably just need to ";
        print l("log in","user/login",array('query' => drupal_get_destination()));
echo " (or ";
print l("register","user/register");
echo " if you don't have a login). If you are having problems accessing a page, registering or logging in please ";
    print l("contact us.","contact");
        }
    else{
echo "Access Denied! You don't have permissions to access this content. If you feel you should have access to it, please ";
    print l("contact us.","contact");
}
?>
soulston’s picture

you can also use tokens for this. You need the token filter module (http://drupal.org/project/token_filter) and also make sure that the token filter is available in the text format you are using:

Create a block and insert this:

<p>If you are already have an account you can <a href="/user/login?destination=[site:current-page:path]">login here</a>.</p>

samwillc’s picture

Hi everyone,

Thanks for this great little snippet! How do I make this into a list though? I need to add the li items somehow but not sure how to do it or where they go amongst the code. This is what I have so far:

<ul class="menu">
<?php
global $user;
    if ($user->uid == 0){
        print l("Sign in","user/login",array('query' => drupal_get_destination()));
        }
    else{
    print l("Logout","user/logout",array('query' => drupal_get_destination()));
}
?>
</ul>

You can see that the output I want is thus:

<ul class="menu">
<li>Sign in</li>
</ul>

Any help is appreciated. Thanks.

Sam.

samwillc’s picture

Hmmm, after a load of trial and error, this seems to work:

<ul class="menu">
<?php
global $user;
    if ($user->uid == 0) {
        echo '<li>';
        print l("Sign in","user/login",array('query' => drupal_get_destination()));
        echo '</li>';
        }
    else {
        echo '<li>';
        print l("Logout","user/logout",array('query' => drupal_get_destination()));
        echo '</li>';
        }
?>
</ul>

Doesn't seem the most graceful but does result in the desired output. Maybe this will help someone.

Sam.

Danny Englander’s picture

Drupal usually prefers the Alternative PHP syntax which gets rid of all the curly braces.

http://drupal.org/coding-standards (see "Alternate control statement syntax for templates" on this page.)

... so your code would look something like this instead.

<?php global $user; ?>

<ul class="menu">
  <?php if ($user->uid == 0): ?>
    <li>
      <?php  print l("Sign in","user/login",array('query' => drupal_get_destination()));  ?>
    </li>
  <?php else: ?>
    <li>
      <?php print l("Logout","user/logout",array('query' => drupal_get_destination())); ?>
    </li>
</ul>

It also gets rid of HTML inside php.

samwillc’s picture

Excellent. Thanks for the tip, always new things to learn! :)

However, this generates an error:

Parse error: syntax error, unexpected $end in /var/sites/t/SITENAME/public_html/modules/php/php.module(80) : eval()'d code on line 12

This? http://www.mydigitallife.info/php-parse-error-syntax-error-unexpected-end/

After adding this line to the bottom of my php.ini file in root:

memory_limit = 128M
extension=pdo.so
extension=pdo_mysql.so 
short_open_tag = On

...the error persists. Need to test the new code locally to try and work out what the problem is.

Sam.

Danny Englander’s picture

oops, you need a closing <?php endif; ?> after the last closing </li>

samwillc’s picture

Thanks :)

You mean here:

<?php global $user; ?>

<ul class="menu">
  <?php if ($user->uid == 0): ?>
    <li>
      <?php  print l("Sign in","user/login",array('query' => drupal_get_destination()));  ?>
    </li>
  <?php else: ?>
    <li>
      <?php print l("Logout","user/logout",array('query' => drupal_get_destination())); ?>
    </li>
  <?php endif; ?>
</ul>

Seems strange that endif goes after the else statement? Although I'm pretty new to php. Works fine, although I need to obviously do some more learning!

Sam.

Danny Englander’s picture

Yep, that's how the alternative syntax works. Glad you got it sorted out! It's also a lot cleaner than all those messy curly braces.

samwillc’s picture

The help is very much appreciated.

Sam.

stefan.korn’s picture

Thanks for this hint: https://drupal.org/node/1569672#comment-7014554, token filter module is very nice for this.

The token [site:current-page:path] did not work for me, instead i have used [current-page:url:path]. I have looked here: https://drupal.org/node/390482#drupal7tokenslist

bharathkumarkn’s picture

This worked for me (for Drupal7)

Add a rule
1) create an event for "User has logged in".
2) Add a condition as you need i.e if you need only a particular user role must be redirected you can add that role in your condition.
3) Add a action system-> page redirect
In the redirect url text area paste this code

  $path = $_SERVER['HTTP_REFERER'];
  if (isset($_GET['current'])) {            //if (isset($_GET['destination'])) {
    $path = $_GET['current'];             // $path = $_GET['destination'];
  }                                               // }
  echo $path;
 

4) save and try to log in. It should work.

ChiKam’s picture

Thanks, this method works well for me, without login redirect module!

Anonymous’s picture

This was a super clean way of implementing without having to set a url for each possible log in location.

Rules also gives you a few nice options about override url set destinations, which could be useful.

brylie’s picture

For some reason the 'value' field for the page redirect is not parsing the PHP. Does this method work with recent version(s) of Rules?

peezy’s picture

The PHP code provided by @bharath only works if the PHP filter module is enabled and you have permission to use it. After enabling and configuring PHP filter, edit your rule's action and put the snippet in the URL Value field.

Be aware of the security implications of enabling the PHP filter module.

Matt B’s picture

You can set 'Force Redirect' to False on the reaction rule, so the rule will not work if there is already a destination parameter present. This simplifies the code snippet to
<?php echo $_SERVER['HTTP_REFERER']; ?>

And don't forget to change the 403 destination on your site settings to 'user'

pczech’s picture

Maybe this will also help. I spent a few hours playing with all those solutions and finally found even simpler one.

My requirement: I don't want to use default login block at all. Instead I want to have a simple link "Log in" shown for anonymous users in the area where "My account" and "Log out" links are shown for authorized user (I use Bartik theme). The link shall be available at every page (like "Log out" link). If the current page is for example node/100 and the user clicks 'Log in' link, then login page (<SITE>/user/login) is shown. After login, the user shall be redirected back to the original page, e.g. node/100. The same redirection shall be done for "Log out" link.

My solution: I've added a new link to User Menu (Structure -> Menus -> User menu: Menu link title: Log in, Path: user/login). Drupal takes care of showing/hiding the link based on whether the user is currently logged in. I noticed that Login Destination module (even without any rule) adds parameter ?current=<CURRENT PAGE> to those Log in, Log out links. To make the redirection working with the login page, it is necessary only to add a rule in Login Destination module and enter <current> in the page path field.

flashon’s picture

After trying out a number of suggestions this worked well for me, thanks! Simple and solid solution. Was surprised that LoginToboggan doesn't provide this functionality as far as I can tell.

Mrvinay99’s picture

But how to do it with rules, Your help will be appreciated.

asubit’s picture

Get the previous URL in PHP :

/**
 * When logout, user stays in same page if it's possible.
 * @param $account
 */
function hook_user_logout($account) {
  $previousUrl= \Drupal::request()->server->get('HTTP_REFERER');
  $response = new Symfony\Component\HttpFoundation\RedirectResponse($previousUrl);
  $response->send();
  return;
}
ressa’s picture

If you want to redirect the user after log in, it's done like this. To redirect to front page, simply change /login_destination to /

/**
 * Redirect user to another page after log in.
 * @param $account
 */
function hook_user_login($account) {
  $response = new Symfony\Component\HttpFoundation\RedirectResponse("/login_destination");
  $response->send();
  return;
}

EDIT: Probably a better solution here: https://www.drupal.org/node/2068293#comment-11931382

Neelanjana Das’s picture

->install the login destination module and check the preserve the destination parameter in the settings page.

This worked for me.

shamilto2000’s picture

This is the simplest way to solve the problem.

leopinzon’s picture

A very easy way that doesn't require so much coding within Drupal is to slightly change de login link adding the current page at the end (or the login page)

example.. before: 

/user/login

after:

/user/login?destinatin=document.location.pathname

This can make the trick

R3m’s picture

<a href="{{ path('user.login', {'destination': path('<current>')}) }}" class="btn btn-primary">{{ 'Connexion'|t }}</a>