How can I determine programatically whether the current user is anonymous or authenticated?
5 Answers
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...
}
-
2Whenever 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, 2015 at 15:39
-
3For anyone else who comes across this, note that \Drupal::currentUser()->isAuthenticated() is the equivalent of D7 user_is_logged_in()– JaypanJan 16, 2017 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. May 30, 2019 at 23:04
$current= \Drupal::currentUser();
if (!$current->id()) {
// is visitor
}
else {
// is logged
}
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.
}
-
Could you explain why
::isAnonymous()
is different fromnot ::isAuthenticated()
? Aug 4 at 1:08
Methods that you can use in Drupal 8 to check:
Use the isAuthenticated() method on the user. For example, use the following code to determine the state of the current user:
$logged_in = \Drupal::currentUser()->isAuthenticated();
Use isAnonymous() to determine if the user is anonymous:
$anynomous_user = \Drupal::currentUser()->isAnonymous();
U can use this code::
global $user;
if ($user->uid == 0) {
//user is not logged in
}else{
//user is logged in
}
-
2
-
2Yeah and use === for strict comparison and put space before and after your else for coding standards :/– klidifiaJul 9, 2019 at 4:45
-
This code could match with an user that is being created, because $user->uid is NULL before the first save(). The NULL response on the uid would match with the == 0.– PauleauDec 8, 2021 at 10:58