0

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(); }
2
  • Can't manage through Router.php?
    – Jackson
    Commented Dec 16, 2016 at 8:48
  • @AnkitShah how can i do it? please elaborate little bit.
    – Naveenbos
    Commented Dec 16, 2016 at 9:42

1 Answer 1

1
# 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
1
  • how to redirect to custom controller with param? Commented Nov 5, 2019 at 11:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.