Drupal Gotcha: Watch out for $user during update.php

Posted: - Modified: | drupal

If you disable access-checking on your update.php, there’s no guarantee that the update script will be run with the superuser as the active user. This could mess up your update functions that delete nodes or use other access permissions.

To fix this, temporarily assume the identity of the superuser in the update functions that need it:

global $user;
$old_user = $user;
$user = user_load(array('uid' => 1));
$session = session_save_session();
session_save_session(FALSE);

and then restore the old user afterwards:

$user = $old_user;
session_save_session($session);
You can comment with Disqus or you can e-mail me at sacha@sachachua.com.