How to programmatically create and log in drupal users

Creating a new user is very easy in Drupal 6. Here's how.
[sourcecode language="php"]


$new_user = array(

'name' => $username,
'mail' => $mail,
'pass' => user_password(),
'status' => 1,
'auth_MODULENAME' => $username

$user = user_save(NULL,$new_user)

// log the user in

$user = user_authenticate($new_user)


Now for the explanation. We create a $new_user array with values we want the newly created user to have. We pass this along to the user_save function and set the 1st parameter as NULL. From the code comments in the user module -

* @param $account
* The $user object for the user to modify or add. If $user->uid is
* omitted, a new user will be added.
* @param $array
* (optional) An array of fields and values to save. For example,
* array('name' => 'My name'); Setting a field to NULL deletes it from
* the data column.

So setting the 1st parameter as NULL creates a new user.

The parameters name, mail, pass and status are all self explanatory. The user_password function generates a random password (by default with a length of 10).

The (optional) 'auth_MODULENAME' element will record the user as being created externally. This will result in an entry in the authmap table like this -

"aid" "uid" "authname" "module"

The user_authenticate function logs the user in. This function expects an array as a parameter. It first loads the user in using the user_load function and in case of no errors logs the user in.

This approach of logging in a user is useful when we have the array with us which contains the raw values used to create the user. If all you have is the uid of the user, then logging the user in is very simple. Just use the global $user object.

[sourcecode language="php"]

global $user

$account = user_load( array('name' => 'USERNAME') ); // or user_load(UID)

$user = $account


Don't use the user_authenticate function here as it expects the raw values(form values). This wil not work -

[sourcecode language="php"]

$account = user_load( array('name' => 'USERNAME') ); // or user_load(UID)



It will take whatever password is stored in the user object(the raw password), md5 it and then run a query to load that user. Since the password in the query is not the raw password but the md5, the query will return nothing. This will cause an error in the user_authenticate function.

For a direct code example for programmatic log in, check the devel module's devel_switch_user function.

share -