How do I check if a user is logged in or not using php

Looking for an If/Else statement so I can display one link if a user is logged in and another if they arent.

Thanks so much,


jsethi’s picture

Oh figured it out!

global $user;
if ($user->uid) {
    Print "This message is only visible for logged-in users.";
if (!$user->uid) {
    Print "This message is only visible for not-logged-in users.";
servantofthebones’s picture

thank you for posting this... found it 1+ year after you posted.

anthonybruno’s picture

Real simple!


Webbeh’s picture

Thanks for this! Simple solution to someone starting out seeing how PHP is integrated with Drupal.

jyuza’s picture

I would STRONGLY advise against the global $user.
Prefer rather $GLOBALS['user'] instead, it is much more secure.

SWMdave’s picture

You might want to throw up an example snippet.

jyuza’s picture

 	if ($GLOBALS['user']->uid==0 || in_array('somerole', $GLOBALS['user']->roles)) { 

This way, only authenticated users can access whatever you want them to with a secure variable.

Imagine some developer wants to alter your own code (where you already set $user).
The dude is going to add his own code below and, like you already did, he is going to need the $user object and (like you did!) call the bastard $user. And BOOM, the man got access to all of the previous $user rights and permissions...

Sk8erPeter’s picture

Why would $GLOBALS['user'] be

"much more secure"

than using global $user?

Uncle_Code_Monkey’s picture

By definition, using "global $user" is equivalent to $GLOBALS['user'] since they both point to the same memory space. Updating one will update the other at the same time. See

If I had to recommend one over the other, I would highly recommend "global $user" as it has better readability. Besides that, PHP 5.4 is making changes to how the $GLOBALS[] array behaves and I suspect this is just the start of such changes. I would not be surprised to see the array deprecated at some point.

Sk8erPeter’s picture

The simplest way is to use user_is_logged_in() function!

jasonflaherty’s picture

if(user_is_logged_in()){ print "Logged In"; }