Drupal - Programmatically create a user and assign a role
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);
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
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);