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.
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).
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With