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(); }
  • Can't manage through Router.php? – Ankit Shah Dec 16 '16 at 8:48
  • @AnkitShah how can i do it? please elaborate little bit. – Naveenbos Dec 16 '16 at 9:42
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
  • how to redirect to custom controller with param? – jafar pinjar Nov 5 '19 at 11:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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