Deleting spam user accounts

If for one reason or another, your site got full of spam user accounts, the easiest way to delete them, in my opinion, is programatically. This way, when a user entity (or object) is deleted, all the other fields that are connected to this entity (like extra user fields or url aliases) are automatically taken care of.

In the different case of trying to delete all this stuff directly in the database (through phpmyadmin or mysql cli), you have to build a quite complicated query that will find all the related data and delete that as well.

So, the steps to accomplish this (for Drupal 7) are the following:

Create a custom module. Let's call it "unspam".

In your unspam.module create a custom path using the hook_menu().

	function unspam_menu() {
  $items['admin/delete-spam-users'] = array (
    'title'            => t('Delete spam user accounts'),
    'description'      => t("Delete spam user accounts"),
    'page callback'    => 'users_cleanup',
    'access arguments' => array('access content'),
  return $items;

In your page callback function create the code that will handle the job.

	function isAdmin($user) { return $user->uid == 1; }
function isNotAdmin($user) { return !isAdmin($user); }
 * Custom function to clear the spam user registrations.
function users_cleanup() {
  $users = entity_load('user');

  echo "Users before cleaning up: " . count($users);

  foreach ($users as $user)
    if (isNotAdmin($user))
        $firstName = $user->field_user_first_name["und"][0]["value"];
        $lastName = $user->field_user_last_name["und"][0]["value"];

        if ($firstName == $lastName ||
            $user->pass == "changeme" ||
            $user->created == $user->login)

  echo "Users after cleaning up: " . count($users);

Within the "if()" condition, implement the criteria that you find useful in your case.

In this example, we delete every account that has an identical first and last name or has a "changeme" password, or the time of the last login is identical to the time of the account creation.

Now, enable the module and navigate to admin/delete-spam-users to put this code to work.

In my case, this code cleared more than 5000 spam user accounts in just a few seconds.

Enjoy a clean site and don't forget to use protection (that is, spam protection)!