Create a user account in Drupal programmatically

DRUPAL 7

<?php
  //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' => 'user_name@example.com',
      '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', 'noreply@example..com'));
  ?>

 

DRUPAL 8

$values = array(
  'name' => 'name',
  'mail' => 'test@gmail.com',
  'roles' => array(),
  'pass' => 'password',
  'timezone'=> 'Indian/Christmas',
  'status' => 1,
);  

$account = entity_create('user', $values);
$account->save();

Tags