Many times, while administering your drupal website, you must have encountered some spam emails. And, you have no way to contact the users. You might want to block the user.

Drupal provides a way to block a user by login from an admin user. But, if you have many users, it will take considerable amount of time to do it one by one.

Blocking User Programmatically

This code assumes, you have email of users you want to block.

Drupal provides an api: user_save(), which takes a loaded user object. And, it can save user in its database.

Code:

$mails = array('<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cbb3b2b18bb3b2b1e5a8a4a6">[emailprotected]</a>', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6a0b08092a0b080944090507">[emailprotected]</a>');

foreach($mails as $ml) {
  $user = user_load_by_mail($ml);
  if (isset($user) && $user->status == 1) {
    $uObj = new stdClass();
    $uObj->uid = $user->uid;
    user_save($uObj, array('status' => 0));
    print "User blocked: ".$user->mail;
  }
print "\n";
}

Understanding Code

First, I load user by email by using api: user_load_by_mail(). Then, I prepare an object by using user uid, and set its status as 0. In drupal, user status of 1 is considered active user.

The API: user_save() is taking 2 parameters. Since, I want to update user. I just passed the object with its uid set. And, in 2nd parameter, I pass the array of attributes I want to update. This ensures, that I do not set any other parameter accidently.

And, it blocks all the user mails passed.