Check if Drupal8 User is Logged In with PHP

How to detect if your user has logged into Drupal
How to detect if your user has logged into Drupal

You can detect with PHP whether a user is logged in with Drupal 8 by using the following code:

$user = \Drupal::currentUser()->isAuthenticated();
// $user will be 1 or 0

Here are the methods available to the \Drupal::currentUser() class as of Drupal 8 Release Candidate 4:

    [0] => setAccount
    [1] => getAccount
    [2] => id
    [3] => getRoles
    [4] => hasPermission
    [5] => isAuthenticated
    [6] => isAnonymous
    [7] => getPreferredLangcode
    [8] => getPreferredAdminLangcode
    [9] => getUsername
    [10] => getAccountName
    [11] => getDisplayName
    [12] => getEmail
    [13] => getTimeZone
    [14] => getLastAccessedTime
    [15] => setInitialAccountId

Tags: