Community Documentation

user_load

5 user.module user_load($array = array())
6 user.module user_load($user_info = array())
7 user.module user_load($uid, $reset = FALSE)
8 user.module user_load($uid, $reset = FALSE)

Loads a user object.

Drupal has a global $user object, which represents the currently-logged-in user. So to avoid confusion and to avoid clobbering the global $user object, it is a good idea to assign the result of this function to a different local variable, generally $account. If you actually do want to act as the user you are loading, it is essential to call drupal_save_session(FALSE); first. See Safely impersonating another user for more information.

Parameters

$uid: Integer specifying the user ID to load.

$reset: TRUE to reset the internal cache and load from the database; FALSE (default) to load from the internal cache, if set.

Return value

A fully-loaded user object upon successful user load, or FALSE if the user cannot be loaded.

See also

user_load_multiple()

▾ 46 functions call user_load()

comment_tokens in modules/comment/comment.tokens.inc
Implements hook_tokens().
DrupalWebTestCase::setUp in modules/simpletest/drupal_web_test_case.php
Generates a random database prefix, runs the install scripts on the prefixed database and enable the specified modules. After installation many caches are flushed and the internal browser is setup so that the page requests will run on the new prefix.…
EntityCrudHookTestCase::testUserHooks in modules/simpletest/tests/entity_crud_hook_test.test
Test hook invocations for CRUD operations on users.
FileValidatorTest::testFileValidateSize in modules/simpletest/tests/file.test
Test file_validate_size().
FilterFormatUpgradePathTestCase::testFilterFormatUpgrade in modules/simpletest/tests/upgrade/upgrade.filter.test
Test a successful upgrade.
FormatDateUnitTest::testFormatDate in modules/simpletest/tests/common.test
Tests for the format_date() function.
hook_tokens in modules/system/system.api.php
Provide replacement values for placeholder tokens.
install_configure_form_submit in includes/install.core.inc
Forms API submit for the site configuration form.
node_preview in modules/node/node.pages.inc
Generate a node preview.
node_tokens in modules/node/node.tokens.inc
Implements hook_tokens().
overlay_user_dismiss_message in modules/overlay/overlay.module
Menu callback; dismisses the overlay accessibility message for this user.
ProfileCrudTestCase::testUserCRUD in modules/profile/profile.test
Test profile integration with user CRUD operations.
profile_block_view in modules/profile/profile.module
Implements hook_block_view().
StatisticsAdminTestCase::testDeleteUser in modules/statistics/statistics.test
Tests that accesslog reflects when a user is deleted.
statistics_user_tracker in modules/statistics/statistics.pages.inc
system_tokens in modules/system/system.tokens.inc
Implements hook_tokens().
theme_node_recent_content in modules/node/node.module
Returns HTML for a recent node to be displayed in the recent content block.
TriggerUserActionTestCase::testUserActionAssignmentExecution in modules/trigger/trigger.test
Tests user action assignment and execution.
UpdateScriptFunctionalTest::testUpdateAccess in modules/system/system.test
Tests access to the update script.
url_alter_test_url_outbound_alter in modules/simpletest/tests/url_alter_test.module
Implements hook_url_outbound_alter().
UserAdminTestCase::testUserAdmin in modules/user/user.test
Registers a user and deletes it.
UserCancelTestCase::testMassUserCancelByAdmin in modules/user/user.test
Create an administrative user and mass-delete other users.
UserCancelTestCase::testUserAnonymize in modules/user/user.test
Delete account and anonymize all content.
UserCancelTestCase::testUserBlock in modules/user/user.test
Disable account and keep all content.
UserCancelTestCase::testUserBlockUnpublish in modules/user/user.test
Disable account and unpublish all content.
UserCancelTestCase::testUserCancelByAdmin in modules/user/user.test
Create an administrative user and delete another user.
UserCancelTestCase::testUserCancelInvalid in modules/user/user.test
Attempt invalid account cancellations.
UserCancelTestCase::testUserCancelUid1 in modules/user/user.test
Tests that user account for uid 1 cannot be cancelled.
UserCancelTestCase::testUserCancelWithoutPermission in modules/user/user.test
Attempt to cancel account without permission.
UserCancelTestCase::testUserDelete in modules/user/user.test
Delete account and remove all content.
UserLoginTestCase::testPasswordRehashOnLogin in modules/user/user.test
Test that user password is re-hashed upon login after changing $count_log2.
UserPictureTestCase::saveUserPicture in modules/user/user.test
UserRolesAssignmentTestCase::userLoadAndCheckRoleAssigned in modules/user/user.test
Check role on user object.
UserSaveTestCase::testUserImport in modules/user/user.test
Test creating a user with arbitrary uid.
UserTokenReplaceTestCase::testUserTokenReplacement in modules/user/user.test
Creates a user, then tests the tokens generated from it.
user_block_user_action in modules/user/user.module
Blocks the current user.
user_cancel in modules/user/user.module
Cancel a user account.
user_category_load in modules/user/user.module
Return a user object after checking if any profile category in the path exists.
user_external_load in modules/user/user.module
Fetches a user object based on an external authentication source.
user_login_submit in modules/user/user.module
Submit handler for the login form. Load $user object and perform standard login tasks. The user is then redirected to the My Account page. Setting the destination in the query string overrides the redirect.
user_pass_reset in modules/user/user.pages.inc
Menu callback; process one time login link and redirects to the user page on success.
user_tokens in modules/user/user.tokens.inc
Implements hook_tokens().
user_uid_optional_load in modules/user/user.module
Load either a specified or the current user account.
user_view_access in modules/user/user.module
User view access callback.
_trigger_normalize_comment_context in modules/trigger/trigger.module
Loads associated objects for comment triggers.
_trigger_normalize_node_context in modules/trigger/trigger.module
Loads associated objects for node triggers.

File

modules/user/user.module, line 361
Enables the user registration and login system.

Code

<?php
function user_load($uid, $reset = FALSE) {
  $users = user_load_multiple(array($uid), array(), $reset);
  return reset($users);
}
?>

Comments

Getting values of user define (custom) fields.

If you have defined custom fields for the user, e.g. firstname, lastname, phone, address, city, etc. and want to get their values, e.g. to display the full username in a block, use $user_fields. For example,

<?php
global $user;
$user_fields = user_load($user->uid);

$firstname = $user_fields->field_firstname['und']['0']['value'];
$lastname = $user_fields->field_lastname['und']['0']['value'];

print 
t("Welcome: " . $firstname. ' ' . $lastname) ;
?>

I think the recommend way is

I think the recommend way is to use field_get_items() function instead of get the value by array.

See also:
http://drupal7ish.blogspot.com/2011/02/proper-way-to-get-field-values.html

Oooh, that's my Drupal 7 blog

Oooh, that's my Drupal 7 blog - there's a better blog entry now with a little function to help you, here:

http://drupal7ish.blogspot.com/2011/03/getting-field-data-out-of-entitie...

And now there's a module with

And now there's a module with a couple of very useful functions for extracting field data from entities:

http://j.mp/piHpfH

Fly my pretties...

No role information returned?

So I have this code in a template:

<?php
$thisuser
= user_load(array('uid' => '11812'));
?>

which, as far as I understand it, should return a user object for the user with the uid of 11812. And that object should contain an array of roles for that user in this variable:
<?php
$thisuser
->roles
?>

But that array doesn't exist.

I've traced through the user_load() function in modules/user/user.module with a debugger, and this code should populate the $user object with that roles array:

<?php
  $result
= db_query('SELECT * FROM {users} u WHERE '. implode(' AND ', $query), $params);

  if (
$user = db_fetch_object($result)) {
   
$user = drupal_unpack($user);

   
$user->roles = array();
    if (
$user->uid) {
     
$user->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user';
    }
    else {
     
$user->roles[DRUPAL_ANONYMOUS_RID] = 'anonymous user';
    }
   
$result = db_query('SELECT r.rid, r.name FROM {role} r INNER JOIN {users_roles} ur ON ur.rid = r.rid WHERE ur.uid = %d', $user->uid);
    while (
$role = db_fetch_object($result)) {
     
$user->roles[$role->rid] = $role->name;
    }
   
user_module_invoke('load', $user_info, $user);
  }
  else {
   
$user = FALSE;
  }
?>

Everything's fine up through this line:
<?php
    $user
= drupal_unpack($user);
?>

but then, when we hit the next line, which should initialize an empty "roles" array in the $user object, nothing happens:
<?php
    $user
->roles = array();
?>

No "roles" array shows up in the object at all. The subsequent db queries work okay, and return the right role information, so this while loop:
<?php
   
while ($role = db_fetch_object($result)) {
     
$user->roles[$role->rid] = $role->name;
    }
?>

has the proper values in $role->rid and $role->name each time through the loop, but $user->roles still doesn't exist, and the assignments here have no effect.

I'm beating my head against this - I can't figure out what's going on. I know that I can just query the db directly in order to get a user's roles if I really must, but why wouldn't the user_load() code work?

Anyone know what's going on?

Thanks.

Username to UID

In Drupal 6 you had the option of specifying a UID or username string as a param in user_load. Now there is only the option of using the UID.

How would you go about getting the UID from username in D7?

user_load_by_name($name)

Hey RobW,
Checkout the user_load_by_name function.

Login or register to post comments