Skip to content

Instantly share code, notes, and snippets.

@hannesl
Created October 10, 2012 09:43
Show Gist options
  • Select an option

  • Save hannesl/3864416 to your computer and use it in GitHub Desktop.

Select an option

Save hannesl/3864416 to your computer and use it in GitHub Desktop.
Delete/cancel a Drupal user programmatically and safely.
// Tell Drupal to cancel this user.
// The third argument can be one of the following:
// - user_cancel_block: disable user, leave content
// - user_cancel_block_unpublish: disable user, unpublish content
// - user_cancel_reassign: delete user, reassign content to uid=0
// - user_cancel_delete: delete user, delete content
user_cancel(array(), $uid, 'user_cancel_reassign');
// user_cancel() initiates a batch process. Run it manually.
$batch =& batch_get();
$batch['progressive'] = FALSE;
batch_process();
@signalpoint
Copy link

13 years later, still works! Thank you.

P.S. Two AIs couldn't get it right.

@bradfordbulger-nasa
Copy link

Trying to run code like this with drush php:script, batch_process() failed, expecting to be running in a web request context. I was able to pull out the relevant parts of that function into the script and it ran OK:

// run the relevant bits of batch_process()
$batch =& batch_get();
$batch['progressive'] = FALSE;
$batch['current_set'] = 0;
\Drupal::moduleHandler()->alter('batch', $batch);
$batch['id'] = 'non-progressive';
foreach ($batch['sets'] as $key => $batch_set) {
  _batch_populate_queue($batch, $key);
}
require_once 'core/includes/batch.inc';
_batch_process();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment