Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

drupal 6 programmatically log user in

Tags:

drupal-6

I'm trying to log in a user as part of a form submit, but why is the following not working:

$user = db_fetch_object(db_query("SELECT * FROM users WHERE mail = '%s' AND pass = '%s'", $mail, md5($pass)));

if ($user) {
    // Authenticate user and log in
    $params = array(
      'name' => $user->name,
      'pass' => trim($user->pass)
    );

    // Authenticate user    
    $account = user_authenticate($params);
}

if I dump $user I can see the correct values, but if I dump the account it's empty.

like image 935
kristian nissen Avatar asked Jul 10 '26 16:07

kristian nissen


1 Answers

You are passing the hashed password to ´user_authenticate()´, while the function expects the clear password (it will hash it itself indirectly when loading the account via ´user_load()´).

So changing your $params array declaration to

$params = array(
  'name' => $user->name,
  'pass' => $pass
);

should make your example work.


BTW, you could use user_load() yourself to avoid querying the database directly:

$user = user_load(array('mail' => $mail, 'pass' => trim($pass), 'status' => 1));

(The 'status' => 1 will restrict results to active users - you can leave that out, of course, if you really want to allow log ins to disabled accounts ;)

like image 56
Henrik Opel Avatar answered Jul 15 '26 14:07

Henrik Opel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!