Create a user account in Drupal 6 programmatically

By shane
Wed, 2011-06-08 15:52
comments

Share with Others

Looking to do this in Drupal 7? See my updated post on how to Create a user account in Drupal 7 programmatically.

There have been a few situations in which I needed to create a user on a Drupal site based on some action. There are many other situations where this might be necessary so I put together a really quick example of how it can work. The code I have below is based heavily on the Ubercart code that creates new users when they purchase a product on an Ubercart powered Drupal site.

  //the user name of the new user
  $user_name = "example";
 
  //the users email address
  $email = "<a href="mailto:example@example.com">example@example.com</a>";
 
  //set up the user fields using a random 8 character password
  $fields = array(
    'name' => $user_name,
    'mail' => $email,
    'pass' => user_password(8),
    'status' => 1,
  );
 
  //you can give a user roles if necessary based on the role name
  $fields['roles'] = array('test_role');
 
  //the first parameter is left blank so a new user is created
  $account = user_save('', $fields);
 
  // 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_admin_created', $email, NULL, array('account' => $account), variable_get('site_mail', '<a href="mailto:noreply@example..com">noreply@example..com</a>'));

Useful? Let me know what you think.