Checking if a user is logged into Drupal (the right way)
I see this regularly when working on Drupal sites when someone wants to check
whether the current user is logged in to Drupal (authenticated) or not
(anonymous).
global $user;
if ($user->uid) {
// The user is logged in.
}
or
global $user;
if (!$user->uid) {
// The user is not logged in.
}
This returns a boolean (TRUE or FALSE) depending or not the user is logged in.
Essentially, it does the same thing as the first example, but there's no need to
load the global variable.
A great use case for this is within a hook_menu() implementation within a
custom module.
There is also a
user_is_anonymous()
function if you want the opposite result. Both of these functions are available
in Drupal 6 and higher.
Was this useful?
About me
I'm an Acquia-certified Drupal Triple Expert with 17 years of experience, an open-source software maintainer and Drupal core contributor, public speaker, live streamer, and host of the Beyond Blocks podcast.