is there a Drupal function to check if the user is logged or not?

Thanks for your support.


nevets’s picture

No function, but it is easy to do, this code snippet should get you going

global $user;

if ( $user->uid ) {
  // Logged in user
else {
  // Not logged in
nimzie’s picture

I am having a very strange thing happen.

In this scenario, the not logged in scenario outputs the string, but the logged in one doesn't. I am using a custom user block with this solution:

template.php contains this function:

function phptemplate_user_login($form) {
return _phptemplate_callback('user_login', array('form' => $form));

Inside my user_login.tpl.php file:

global $user;

if ( $user->uid ) {
  print Logged;
else {
  print not;

I'm going to guess that user_login.tpl.php doesn't even get run when the user is logged in? Does anyone know how to arrange this otherwise?

Could it have to do with the "me" module?

I want the username/pass only in my login block (when not logged in)
When logged in, I want to see a logout link.
I figure this scenario 'should' work, but I have a hunch the custom template isn't even run when logged out.

Is there another "simple" way to do this? I've seen a few articles around but nothing doing just this.

I've searched all around DrupalLand. There are a tonne of resources for this simple task.

Could there be a config issue I'm missing?

nevets’s picture

How about two blocks? Use the standard login block for one and a custom block for the logout link with visibility set so it only shows for people logged in.

skhani’s picture

This wont work because anonymous user still has a uid

Jaypan’s picture

That's incorrect. Anonymous users have a UID of 0 (zero). Zero in PHP evaluates to FALSE. Therefore the following code does work for checking if a user is logged in or not.

global $user;

  // user is logged in
  // user is not logged in
mahesh_kharote’s picture

Hi nevets,

I am newbie to drupal, were this code is to be placed in order to check whether user is logged in if he/she wishes to view some content that would be visible for only those user who are logged in.

Thanks in advance.

saitanay’s picture

will that work with drupal 6

Ivan Zugec’s picture

Yes it will work in drupal 6.


grobemo’s picture

Starting in Drupal 6.x, there is a function to check whether the user is logged in: user_is_logged_in()

aliyakhan’s picture

Hey Thank, it worked...

Aliya Khan, Front End Developer

parisek’s picture

For Drupal 6+ use this function user_is_logged_in()

jasonflaherty’s picture

Use the user_is_logged_in() function like so:

if(user_is_logged_in()){ print "Logged In"; }
jfcolomer’s picture

PHP snippet

global $user;
if ($user->uid):
  // Then...

Proper way

if (user_is_logged_in()) {
  // Then...
jo_as_neo’s picture

Also, in pretty much every templates, $logged_in (boolean) is available.

if ($logged_in) {
  // Then...