Magento PHP check if user is logged in
13,203
Solution 1
In magento 1.9, if you want to check if the user is logged in any controller or phtml, you need to add
<?php
if( ! Mage::getSingleton('customer/session')->isLoggedIn()){
//not logged in
}else{
// logged in
}
?>
the important part to intance the super object is this
Mage::getSingleton('customer/session')
Solution 2
In Magento 2.x PHP check if user is logged in (phtml file), you can use below code:
$authorizationLink = $block->getLayout()->createBlock('Magento\Customer\Block\Account\AuthorizationLink');
<?php if($authorizationLink->isLoggedIn()){
// Customer is logged In
}else{
// Customer is not logged In
}
?>
Solution 3
It's because of echo $block->getLinkAttributes()
This is block is vendor\magento\framework\View\Element\Html\Link.php and it is not called as $block on every page , so if you need getLinkAttributes() you need to call it manually.
Author by
Mark
Updated on June 07, 2022Comments
-
Mark almost 2 years
I have the following code to see if a user is logged in. It sort of works as in it works within the customer area (user logged in) but doesn't work outside of the customer area even though the customer is still logged in.
<?php $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $customerSession = $objectManager->get('Magento\Customer\Model\Session'); if($customerSession->isLoggedIn()) { ?> <li class="link wishlist" data-bind="scope: 'wishlist'"> <a <?php /* @escapeNotVerified */ echo $block->getLinkAttributes() ?>><?php echo $block->escapeHtml($block->getLabel()) ?> <!-- ko if: wishlist().counter --> <span data-bind="text: wishlist().counter" class="counter qty"></span> <!-- /ko --> </a> </li> <li>Hello World</li> ?> <?php } else { ?> <li>Not logged in</li> <?php } ?> <script type="text/x-magento-init"> { "*": { "Magento_Ui/js/core/app": { "components": { "wishlist": { "component": "Magento_Wishlist/js/view/wishlist" } } } } } </script>
-
user3478148 almost 8 yearsTake a look at the code he's using. This is Magento 2, not Magento 1.9. He should've specified that though.
-
Ahdee almost 6 yearsCan confirm this works with Magento 2.1: this is perfect thanks.
-
jafar pinjar about 5 yearshow to get customer name in this class
-
Black about 4 yearsShould not use objectManager
-
Black about 4 yearsobjectManager is a dirty way
-
Black about 4 yearsThats dirty, you should never use objectManager. And you have to add code in the block class and then just call it in the template
-
open-ecommerce.org almost 4 yearsnot sure why but session wasn't working in 2.3.5 and this way works just fine