Create a user account in Drupal 7 programmatically

By shane
Wed, 2012-06-27 21:18

Share with Others

As a follow up to my post on how to create a user account in Drupal 6 programmatically, I ran into a situation where I needed to do this in Drupal 7. Pretty similar but a few differences. So here you go:
  //This will generate a random password, you could set your own here
  $password = user_password(8);
  //set up the user fields
  $fields = array(
    'name' => 'user_name',
    'mail' => '',
    'pass' => $password,
    'status' => 1,
    'init' => 'email address',
    'roles' => array(
      DRUPAL_AUTHENTICATED_RID => 'authenticated user',
  //the first parameter is left blank so a new user is created
  $account = user_save('', $fields);
  // If you want to send the welcome email, use the following code
  // Manually set the password so it appears in the e-mail.
  $account->password = $fields['pass'];
  // Send the e-mail through the user module.
  drupal_mail('user', 'register_no_approval_required', $email, NULL, array('account' => $account), variable_get('site_mail', ''));
Note: You can add additional roles inside the role array using the role id as the array index and the role name as the value.
Questions? Let me know in the comments below.