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,
Jay

Comments

jsethi’s picture

Oh figured it out!

<?php
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!

Cheers!

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.

Check Out KarmaLynx.com for your Social Bookmarking needs. Built with Drupal and Sharing the Karma!

jyuza’s picture

<?php
    
if ($GLOBALS['user']->uid==0 || in_array('somerole', $GLOBALS['user']->roles)) {
      
drupal_access_denied();
       exit();
    }
?>

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 http://php.net/manual/en/reserved.variables.globals.php

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

<?php
if(user_is_logged_in()){ print "Logged In"; }
?>