Drupal user login - How to tell if a Drupal user is logged in (authenticated)

Drupal user login FAQ: How can I test to see if a Drupal user is logged in (authenticated)?

If you’re creating a theme in Drupal, working with an existing Drupal theme, or developing a Drupal module, you may need to know whether a visitor to your Drupal website is currently logged in (an authenticated user), or whether they are not logged in (an anonymous user). Here's how to test to see if a Drupal user is logged in.

Drupal user login test

Fortunately there's an easy way to determine the Drupal user login status in your Drupal theme or module. You can just use the user_is_logged_in method in combination with an if/else statement.

I just did this in my Drupal theme page.tpl.php page, similar to this:

<?php if (user_is_logged_in()): ?>

  <p>Hello, logged in user</p>

<?php else:?>

  <p>Hello, stranger</p>

<?php endif;?>

What I really do is use this test to toggle the display of "Login" and "Logout" links on my website (but that code is a little more complicated, and I want to keep this example simple). When a Drupal user is in the "anonymous user" state, I show the Login link; and when they’re logged in, I show the Logout link in the same location.

For authenticated Drupal users, you can get more information about the user from the Drupal $user object, but for the purpose of telling whether a user is logged in or not, this simple test works great.

The Drupal $logged_in variable

As one more quick note, on this page.tpl.php Drupal API documentation page, I see there is also a $logged_in variable that you can use for the same purpose. I haven’t tested this, but you should just be able to replace the method call shown above with this variable. For instance, if you want to emit some <p> tag content if a user is NOT logged in, this code should work:

<?php if (!$logged_in): ?>
  <p>Whatever you want to output here ...</p>
<?php endif;?>

Drupal version information

This code was tested with Drupal 6.x.

Drupal login problems

On a related note, if you're having problems logging into your Drupal website, see my article "Help, I can't login to my Drupal website". While that article talks about login problems after a Drupal upgrade, the same problems can occur in other ways.