Drupal 7: PHP snippet to add users from a list

Here is a very crude PHP snippet that can be used to add a list of users to a Drupal site.

The code can be added to a Drupal block with content type "PHP Code", which is then added to some page and made visible only to the site administrator (using e.g. the `roles' tab on the block configuration page).

$participants = "
Joe' Sbdy $ mail@dress.com
Joe B' Smith $ mail.ii@dress.com
foreach(preg_split("/(\r?\n)/", $participants) as $line){
  $tokens = explode( '$', $line );
  $new_email = trim( array_pop( $tokens ) );
  $tokens = explode( "'", $tokens[0] );
  $new_uname = trim( $tokens[0] );
  if ( user_load_by_mail( $new_email ) == FALSE) {  
    $newUser = array(  
      'name' => $new_uname,  
      'pass' => user_password(),
      'mail' => $new_email,  
      'status' => 1,
      'access' => '0',
    $account = user_save(null, $newUser);  
    $dmailrval = _user_mail_notify('register_admin_created', $account);  
    echo "Say hello to $new_uname &lt;$new_email&gt;<br />";
  }  else {
    echo "User $new_uname exists?<br />";

In the example, the usernames and email addresses are organized as a string, with newlines separating users, and a $ on each line, separating the user's name from the email address.

There's no checking for username uniqueness; the script simply takes the person's name from the list, up to the character ' – which can be inserted in order to make unique names without having to include the full name – to generate the username.

The new users will be notification by email — so you have to configure notifications first [at admin/config/people/accounts, the "Welcome (account created by administrator)" tab].