Drupal: Make a Context-Aware User Login Link (PHP Snippet)

Many of the sites I design don't require a user login form on every page, especially if there are only a few people that will ever need to login. Instead, I like to simply provide a "User Login" link somewhere on the page (most often in the footer), so it's unobtrusive but there for those who might not remember to type in /user after the URL.

This presents a new problem, though: if you put a link to "example.com/user," then the person who clicks the link will be taken away from the page he was viewing to login, then he'll be directed to his user account page.

Luckily, Drupal lets you set a login destination in the URL, so you can redirect the user back to the page he was viewing after he logged in.

To do so, create a block with PHP as the input format (or insert this snippet somewhere in your .tpl.php template files), and use the code below:

<a href="/user?destination=<?php echo $_GET['q']; ?>">User Login</a>

Now you have a handy little link that will redirect a user back to the page he was viewing before he logged in.