Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

drupal 7 programmatically log user in

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.

like image 231
Felix Eve Avatar asked Nov 10 '11 10:11

Felix Eve


2 Answers

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).

like image 117
Ken Avatar answered Nov 10 '22 04:11

Ken


Drupal does it using user_login_finalize from user_login_submit, you can invoke the same thing yourself with this code:

$form_state['uid'] = $account->uid;
user_login_submit(array(), $form_state);
like image 14
Clive Avatar answered Nov 10 '22 05:11

Clive