feelin’ good

Drupal: Working With Users

This short notes corresponds to “Chapter 6: Working With Users” of the book Pro Drupal Development by John K. Vandyk and Matt Westgate. See “Drupal: Working With Databases” for my notes on Chapter 5.

The $user Object

To log in, the user must have cookies enabled; otherwise, the user is treated as an anonymous user.

The user is represented as the global $user object, which is created during the session phase of the bootstrap process. The $user object is a join of all the fields in the users table and sessions table on the user’s ID. The anonymous user is created by drupal_anonymous_user() and looks like this:

function drupal_anonymous_user($session='') {

$user = new stdClass();
$user->uid = 0;
$user->hostname = $_SERVER['REMOTE_ADDR'];
$user->roles = array();
$user->roles[DRUPAL_ANONYMOUS_RID] = 'anonymous user';
$user->session = $session;

return $user;

To see the contents of the $user object, do

global $user;
print_r $user;

which prints (for a logged-in user):

stdClass Object {

// Provided by the users Table

[uid] => 2 //Primary key of users table
[name] => Joe Example
[pass] => 9789adf798a7d8f //MD5 hash of the password
[mail] =>joe@example.com //Current email
[mode] => 0 //Comment-viewing preference
[sort] => 0 //Comment-viewing preference
[threshold] => 0 //Comment-viewing preference
[theme] => chameleon //User's chosen theme
[signature] => Drupal rocks! //Visible in user's comment
[created] => 1161112061 //Unix timestamp
[access] => 1161112061 //Unix timestamp
[login] => 1161112317 //Unix timestamp
[status] => 1 //0 means user is blocked
[timezone] => -18000 //Number of seconds that is offset from GMT
[language] => en //Set by locale_initialize() in common.inc.
[picture] => files/pictures/me.jpg
[init] => joe@example.com //Initial email upon registration
[data] => //Arbitrary data stored by modules

//Provided by the user_roles Table

[roles] => Array ( [2] => authenticated user )

//Provided by the sessions Table

[sid] => 7a89sdf8glj4j345jlk43lkj5 //Session ID assigned by PHP
[hostname] => //IP address of user
[timestamp] => 1161113476 //Unix timestamp of the time the user last received a completed page
[cache] => 0 //Timestamp used for per-user caching
[session] => user_overview_filter|a:0:{} //Arbitrary data stored by modules for the duration of the session


Storing Data in the $user Object

The data field in the users table is for holding extra information in a serialized array. To store data, call user_save():

global $user;
$extra_data = array('disposition' => t('Grumpy'));
user_save($user, $extra_data);

To retrieve data, do:

global $user;
print $user->disposition; //Prints 'Grumpy'

This method creates additional overhead, because the data needs to be unserialized. An alternative method is to implement hook_user('load'), see below.

Testing if a User Is Logged In

Simply test whether $user->uid is 0.

Introduction to hook_user()

Implement hook_user() If you want to perform some operations when an action occurs on the user account (such as login or view):

function hook_user ($op, &$edit, &$user, &category=NULL)

$op says what the action that has occurred on the user account is. For details on the values that $op can take, see the Drupal API.

$edit is the array of form values, for use when $op involves a form.

$user is the user object for the account that the action occurs on. It may be different from the global $user object, which is the user currently logged in.

$category is the category of user information being edited.

Using hook_user(‘view’)

To add information to user profile pages, implement hook_user() to detect when $op = 'view'. For example, the blog module adds a link to user profile pages by:

function blog_user($op, &$edit, &$user) {

if ($op == 'view') {

$items['blog'] = array(
'title' => t('Blog'),
'value' => l(t('View recent blog entries'), "blog/$user->uid"),
'class' => 'blog'

return array(t('History') => $items);

An alternative way is to implement hook_profile_alter(), which manipulates profile items before they are rendered by theme_user_profile() in user.module. Here the hook is implemented to hide the blog link:

function hide_profile_alter(&$account, &$fields) {



The User Registration Process

To add your own fields to the user registration form, implement hook_user('register'), hook_user('validate'), and hook_user('insert').

Using profile.module to Collect User Information

Instead of creating your own module, the profile module can be used to add your own fields to the user registration form. The profile module will also automatically create profile summary pages if the field’s Page title is field, and the field is not of type textarea, URL or date.

The Login Process

In the login form’s validation routine, the username is checked against blockage, access rule, and password. If the username passes validation, hook_user('load') and hook_user('login') are invoked.

Besides local authentication, external authentication, such as LDAP, Pubcookie, and Sxip, as well as distributed authentication, whereby users from one Drupal site can log on to another, can also be used. External authentication is only used when local authentication fails.

Adding Data to the $user Object

This can be done with hook_user('load').

Providing User Info Categories

To add information categories, use profile.module or implement hook_user('categories'). For an example see profile_user() in profile.module.

External Login

(Read it, but did not try to summarize, because I will not be using it.)


9 responses

  1. Hi! I was surfing and found your blog post… nice! I love your blog. :) Cheers! Sandra. R.

    September 10, 2009 at 9:17 pm

  2. Mark

    Where the form is stored?
    How to create a user after when the form is submitted?

    April 1, 2010 at 6:43 pm

  3. thank you :)

    June 7, 2010 at 4:09 am

  4. Sign: wdpad Hello!!! vdcae and 8041teenwkpzmt and 4184 : Cooooool blog really

    August 11, 2010 at 1:24 am

  5. PiersG

    The code

    ‘value’ => l(t(‘View recent blog entries’), “blog/$user->uid”),

    would generate the errors described in http://drupal.org/node/893682 and needs to be corrected to something like (although I’ve *not* tried it)
    ‘value’ => l(t(‘View recent blog entries’), ‘blog/%uid’), array(‘%uid’ => $user->uid)),

    April 18, 2011 at 1:52 am

  6. http://andcarinsurancequotes.com

    Many thanks for being my coach on this topic. My spouse and i enjoyed your article very much and most of all cherished how you handled the aspect I widely known as controversial. You happen to be always incredibly kind towards readers much like me and assist me in my existence. Thank you.

    March 19, 2012 at 10:26 am

  7. Nice! New post! You’ve clearly been working on your writing skills. Good show :) Thank you so much for the cleverness of well – you!

    August 4, 2012 at 6:13 am

  8. hey there and thank you for your info – I have certainly picked up something new from right here.
    I did however expertise several technical issues using this website, as I experienced to reload the
    website many times previous to I could get it to load
    properly. I had been wondering if your hosting is
    OK? Not that I am complaining, but slow loading instances
    times will sometimes affect your placement in google and
    can damage your high-quality score if advertising and marketing with
    Adwords. Anyway I am adding this RSS to my email and could look out
    for a lot more of your respective exciting content. Make sure you update this
    again soon.

    September 18, 2012 at 12:19 pm

  9. Great web site you’ve got here.. It’s difficult to find high quality writing like yours these days.

    I truly appreciate individuals like you! Take care!!

    August 5, 2014 at 7:18 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s