How to redirect a user after login to a specific page

There are some simple Drupal modules that help with login redirection (especially Login Destination), but I often need more advanced conditions applied to redirects, so I like being able to do the redirect inside a custom module. You can also do something similar with Rules, but if the site you're working on doesn't have Rules enabled, all you need to do is:

  1. Implement hook_user_login().
  2. Override $_GET['destination'].

The following example shows how to redirect a user logging in from the 'example' page to the home page (Drupal uses <front> to signify the home page):

<?php
/**
 * Implements hook_user_login().
 */
function mymodule_user_login(&$edit, $account) {
 
$current_path = drupal_get_path_alias($_GET['q']);

 
// If the user is logging in from the 'example' page, redirect to front.
 
if ($current_path == 'example') {
   
$_GET['destination'] = '<front>';
  }
}
?>

Editing $edit['redirect'] or using drupal_goto() inside hook_user_login() doesn't seem to do anything, and setting a Location header using PHP is not best practice. Drupal uses the destination parameter to do custom redirects, so setting it anywhere during the login process will work correctly with Drupal's built in redirection mechanisms.

Comments

I think hook_user_login() fires after someone uses the password reset link (if I'm not mistaken), so this should work there, too. But test and see :)

I really really suggest using login_destination module instead, which also has an API.

It is much simpler to use and has support for certain edge cases that can cause very weird errors.

For most cases, I do use login destination (I've also added a link in the intro above); but every once in a while I need to do something that login destination can't handle as simply. It does fit 95+% of use cases I've seen.