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).

<?php
$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].

Comments

Thanks, help me a lot.

Greetings from barcelona

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Markdown

  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • Web page addresses and e-mail addresses turn into links automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.