Thursday, May 6, 2010

How To Create Users Programmatically In Drupal 6.x

Here's a quick code snippet you can use to programmatically create new users in Drupal 6.x:

<?php
$rid = array_search('a role name', user_roles(true));

$newUser = array(
  'name' => 'username',
  'pass' => user_password(), // note: do not md5 the password
  'mail' => 'email address',
  'init' => 'email address',
  'status' => 1,
  'roles' => array($rid => ''), // user_save() extract the "key" instead of value.
  'language' => variable_get('language_default', 'en'),
  'timezone' => variable_get('date_default_timezone', '-25200'),
  'timezone_name' => variable_get('date_default_timezone_name', 'America/Vancouver'),
);           
user_save(null, $newUser);
?>
And, here's how you can update an existing user:

<?php
// load user object
$existingUser = user_load('USERID');

// update some user property
$existingUser->some_property = 'blah';

// save existing user
user_save((object) array('uid' => $existingUser->uid), (array) $existingUser);
?>

If you are creating a new user, you can get the uid like this:

<?php
$user = user_save(null, $newUser);

$new_user_id = $user->uid;
?>

See http://api.drupal.org/api/function/user_save for more details.

1 comment:

Anthony Perez said...

What you don't do is describe how to use this in drupal or in a block module... Can you explain how you used it what it can be used for or why you would do this?