drupal 7 programmatically log user in

Felix Eve picture Felix Eve · Nov 10, 2011 · Viewed 22.2k times · Source

After having just registered a new account and created a profile how would I log a user in?

I have tried :

global $user;
$user = user_load($account->uid);

or

global $user;
$user = user_load(array('mail' => $_POST['email'], 'pass' => trim($_POST['password'])));

but neither work and the second results in an error about array_flip.

Answer

Ken picture Ken · Dec 11, 2012

I'm going to answer this for future reference, because the third answer above is wrong, and the first answer will work but is unnecessary (it replicates the experience of the user submitting the login form, calling all validators etc, and presumably you have already done that validation or you wouldn't be trying to log the user in directly.

This will work as expected, assuming you have $username and $password from your own form or function, and you know the user is not logged in:

if ($uid = user_authenticate($username, $password)) {
  global $user;
  $user = user_load($uid);

  $login_array = array ('name' => $username);
  user_login_finalize($login_array);
}

First you validate the username and password you have. If you get back a non-zero UID, the authentication succeeded. You create an array that provides the one possibly necessary piece of information that was in the original login form, and pass it to user_login_finalize(), which does all the rest (not just regenerating the session, but also recording the login properly, and calling login hooks).