Skip to content
This repository has been archived by the owner on Feb 7, 2021. It is now read-only.

How to check if the user is logged in

Eric Richer edited this page Jul 10, 2020 · 1 revision

Task

Check if the user is logged in (ie: user identity widget)

Solution

There are three ways.

View

LmcUser provides a View Helper (lmcUserIdentity) which you can use from any view script in your application.

<!-- Test if the User is connected -->
<?php if(!$this->lmcUserIdentity()): ?>
    <!-- display the login form -->
    <?php echo $this->lmcUserLoginWidget(array('redirect'=>'application')); ?>
<?php else: ?>
    <!-- display the 'display name' of the user -->
    <?php echo $this->lmcUserIdentity()->getDisplayname(); ?>
<?php endif?>

You can also get user's fields (if the user is logged in), like email:

<?php echo $this->lmcUserIdentity()->getEmail(); ?>

Controller

LmcUser provides a Controller Plugin (lmcUserAuthentication) which you can use from any controller in your application. You can check if the user is connected and get his data:

<?php
if ($this->lLmcUserAuthentication()->hasIdentity()) {
    //get the email of the user
    echo $this->lmcUserAuthentication()->getIdentity()->getEmail();
    //get the user_id of the user
    echo $this->lmcUserAuthentication()->getIdentity()->getId();
    //get the username of the user
    echo $this->lmcUserAuthentication()->getIdentity()->getUsername();
    //get the display name of the user
    echo $this->lmcUserAuthentication()->getIdentity()->getDisplayname();
}
?>

You can get the zfcuser_auth_service in a controller by doing:

$authService = $this->lmcUserIdentity()->getAuthService();

Service Manager

<?php
$sm = $app->getServiceManager();
$auth = $sm->get('zfcuser_auth_service');
if ($auth->hasIdentity()) {
    echo $auth->getIdentity()->getEmail();
}
?>