51

I'm programmatically creating a user with the following code.

$newUser = array(
  'name' => $mail, 
  'pass' => 'password',  // note: do not md5 the password
  'mail' => $mail, 
  'status' => 1, 
  'init' => $mail,
  'roles' => array(5)
);
$user = user_save(null, $newUser);

I have got a role with the role ID equal to 5; when I create the user, in the table "users_roles" there is only a row with the value 0 for the role ID, but if I print the user object with var_dump(), it looks like the roles are created.

What am I doing wrong?

1
  • It only checks for truthiness on the value, the key is what matters. array($role_id => 'anything') Jul 31, 2019 at 16:06

6 Answers 6

48

This code worked for me:

$new_user = array(
  'name' => $name,
  'pass' => $sifra, // note: do not md5 the password
  'mail' => $email,
  'status' => 1,
  'init' => $email,
  'roles' => array(
    DRUPAL_AUTHENTICATED_RID => 'authenticated user',
    3 => 'custom role',
  ),
);

// The first parameter is sent blank so a new user is created.
user_save('', $new_user);
4
  • Should i write the password a password like "abc12345" and user_save() will convert into md5?
    – xstean
    Nov 18, 2015 at 20:02
  • 2
    user_save will take care of it
    – Gulok
    Feb 16, 2017 at 5:01
  • As long as the password is in user_save()'s second argument, it will get hashed. If you do user_save($account) without the $edit argument, then md5 conversion doesn't happen. The answer by @SMTF below demonstrates this.
    – alec
    Jan 11, 2019 at 15:59
  • Thanks saved my day
    – Rishab
    Sep 20, 2019 at 9:06
16

To programmatically create a user with roles and custom field values (like e.g. First Name and Last Name) you can use the following code:

$new_user = array(
  'name' => 'xgramp',
  'pass' => 'idontwantnoonebutyoutoloveme',
  'mail' => '[email protected]',
  'signature_format' => 'full_html',
  'status' => 1,
  'language' => 'en',
  'timezone' => 'America/Los_Angeles',
  'init' => 'Email',
  'roles' => array(
    DRUPAL_AUTHENTICATED_RID => 'authenticated user',
    6 => 'member', // role id for custom roles varies per website
  ),
  'field_first_name' => array(
    'und' => array(
      0 => array(
        'value' => 'Gram',
      ),
    ),
  ),
  'field_last_name' => array(
    'und' => array(
      0 => array(
        'value' => 'Parsons',
      ),
    ),
  ),
);

$account = user_save(NULL, $new_user);

See this blog post and the comments for more details: http://codekarate.com/blog/create-user-account-drupal-7-programmatically

0
13

This is an example I found on a site.

$account = new stdClass;
$account->is_new = TRUE;
$account->name = 'foo';
$account->pass = user_hash_password('bar');
$account->mail = '[email protected]';
$account->init = '[email protected]';
$account->status = TRUE;
$account->roles = array(DRUPAL_AUTHENTICATED_RID => TRUE);
$account->timezone = variable_get('date_default_timezone', '');
user_save($account);
4
  • Sorry, I think the DRUPAL_AUTHENTICATED_RID => TRUE seems wrong, and I don't think user_hash_password is needed. Mar 16, 2016 at 16:43
  • user_hash_password('bar'); is wrong
    – Joel James
    Nov 7, 2016 at 8:43
  • There are some instances where user_save() fails to hash passwords before saving them (in my own experience and I see others around the web also experiencing it occasionally). I don't know why (but I'd like to!). In these cases calling user_hash_password() seems necessary.
    – alec
    Jan 10, 2019 at 19:05
  • The code in this answer does require user_hash_password() to be called manually. This is because it's not passing $edit to the user_save(). If the code includes $edit = array('pass' => 'bar'); (which this answer does not) then instead of doing $account->pass = user_hash... you can do user_save($account, $edit); and user_save() will do the hashing for you.
    – alec
    Jan 11, 2019 at 15:53
3

To create a user programmatically from an e-mail address, try this:

// Use the e-mail address prefix as a user name.
$name = substr($mail, 0, strpos($mail, '@'));

// Make sure the user name isn't already taken.
$query = db_select('users', 'u')
  ->fields('u', array('uid'))
  ->condition('u.name', $name)
  ->execute();
$result = $query->fetch();

// If the user name is taken, append a random string to the end of it.
if ($result->uid) { $name .= '-' . user_password(); }

// Build the user account object and then save it.
$account = new stdClass();
$account->name = $name;
$account->mail = $mail;
$account->init = $mail;
$account->pass = user_password();
$account->status = 1;
user_save($account);
if ($account->uid) {
  drupal_set_message('Created new user with id %uid', array('%uid' => $account->uid));
}
1

To create user in Drupal 8

  // Mandatory user creation settings
  use Drupal\user\Entity\User;
  $user = User::create();
  $language = 'en'; //you can set your language
  $email = '[email protected]';
  $user_name = 'ajay_gadhavana';
  $user->enforceIsNew();
  $user->setPassword('Password');
  $user->setEmail($email);
  $user->setUsername($user_name); // This username must be unique and accept only a-Z,0-9, - _ @ .
  $user->set("langcode", $language);
  // Optional settings
  $user->set("init", $email);
  $user->set("preferred_langcode", $language);
  $user->set("preferred_admin_langcode", $language);
  $user->activate();
  // Add a role to user
  $user->addRole('administrator');
  //Save user
  $user->save();`
0

To create a user programmatically:

$newUser = array(
      'name' => 'theUserName,
      'pass' => 'thePassWord',
      'mail' => '[email protected]',
      'status' => 1,
      'roles' => array(DRUPAL_AUTHENTICATED_RID => 'authenticated user'),
      'init' =>  '[email protected]',
  );
user_save(null, $newUser);

This site is temporarily in read-only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .