How can I determine programatically whether the current user is anonymous or authenticated?


For the sake of more robust and descriptive code, you can make use of the handy User::isAnonymous() method, e.g.

if (\Drupal::currentUser()->isAnonymous()) {
  // Anonymous user...
|improve this answer|||||
  • 2
    Whenever possible, use methods like this: program to the interface not the implementation. Using an IDE w/ code completion is invaluable for Drupal 8 work. – mpdonadio Feb 2 '15 at 15:39
  • 3
    For anyone else who comes across this, note that \Drupal::currentUser()->isAuthenticated() is the equivalent of D7 user_is_logged_in() – Jaypan Jan 16 '17 at 8:13
  • I created a custom module and I can't get this function to work. Is there something additional I need to add in my module? Thank you in advance. – SuperTony May 30 '19 at 23:04
  $current= \Drupal::currentUser();
  if (!$current->id()) {
    // is visitor
  else {
    // is logged
|improve this answer|||||

isAnonymous() holds the danger of not working when a site is saving data (for example in forms) in PrivateTempStore. Therefore, i prefer the following:

if (\Drupal::currentUser()->isAuthenticated()) {
  // This user is logged in.
} else {
  // This user is anonymous.
|improve this answer|||||

U can use this code::

global $user;
if ($user->uid == 0) {
  //user is not logged in
  //user is logged in
|improve this answer|||||
  • 2
    Drupal code works for Drupal 7, but not in Drupal 8 – Dev May 25 '17 at 12:26
  • 1
    Yeah and use === for strict comparison and put space before and after your else for coding standards :/ – klidifia Jul 9 '19 at 4:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.