Question

I want to write a script for redirection, i would like to write this script in Magento 2 header.phtml file, i have tried this below method but it is going to an infinite loop. Any one have any idea about this?

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$customerSession = $objectManager->get('\Magento\Customer\Model\Session'); $urlInterface
= $objectManager->get('\Magento\Framework\UrlInterface');

if(!$customerSession->isLoggedIn()) {
    $customerSession->setAfterAuthUrl($urlInterface->getCurrentUrl());
    $customerSession->authenticate(); }
Was it helpful?

Solution

# check if user is logged in
  $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
  $customerSession = $objectManager->get('Magento\Customer\Model\Session');

  if(!$customerSession->isLoggedIn())
  {
    $request = $objectManager->get('Magento\Framework\App\Request\Http');
    //get instance for URL interface
    /** @var \Magento\Framework\UrlInterface $urlInterface */
    $urlInterface = $objectManager->get('Magento\Framework\UrlInterface');
    // URL to redirect to
    $url = $urlInterface->getUrl('customer/account/login');

    if(strpos($request->getPathInfo(), '/customer/account/') !== 0)
    {
        # redirect to /customer/account/login    

         header('Location:'.$url );die();

    }
  }

Please do static content deploy after placing this code in your phtml.

sudo php bin/magento setup:static-content:deploy
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top