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 view 4 comments or e-mail me at sacha@sachachua.com.

4 comments

Hey Sacha. I really loved your DrupalCon presentation!!!......... Considering this blog post, I think you'll enjoy this Drupal.org issue:
http://drupal.org/node/67234

RTFVerterra

2009-03-24T13:47:01Z

I am not sure if this is connected to your post, but I don't understand why Drupal was designed in such a way that user 1 can be deleted by another user with "user admin" privilege. I've been to this trouble, fortunately, its a dev site. Reinstall was my ultimate solution.

Might be time to hack core? ;)

You could also access the database directly and change your user's UID to 1, if that works...

RTFVerterra

2009-03-24T23:10:01Z

I am not comfortable in dealing with database tables. I am not a developer, my experiences with Drupal are mostly achieved by trial and error approach. I can navigate through mySQL tables, but I never attempt to touch any record. Though I understand now the codes in page.tpl.php, my codes are all copy-pasted. :)