2

In native php we can display url referrer by echo $_SERVER['HTTP_REFERER'];.

Now by Magento 2 i want to do the same thing, i have tried echo $this->getRefererUrl();, but it gives me page not found without error.

What is the proper way to display referer url in Magento 2?

Seventh St
  • 727
  • 3
  • 15
  • 32

2 Answers2

2

Just keep $this->_redirect->getRefererUrl(); line and get Referer url in magento 2.

namespace Test\Modulename\Controller\Index;
use Magento\Framework\Controller\ResultFactory; 

class Index name extends \Magento\Framework\App\Action\Action
{      
    public function execute()
    {
        $referralUrl = $this->_redirect->getRefererUrl();
    }
}
Teja Bhagavan Kollepara
  • 3,816
  • 5
  • 32
  • 69
Rakesh Jesadiya
  • 42,221
  • 18
  • 132
  • 183
1

In the controller, you can get the referer url by using \Magento\Framework\App\Response\RedirectInterface.

For example: vendor/magento/module-customer/Controller/Account/Edit.php

    /** @var \Magento\Framework\View\Result\Page $resultPage */
    $resultPage = $this->resultPageFactory->create();

    $block = $resultPage->getLayout()->getBlock('customer_edit');
    if ($block) {
        /** @var \Magento\Framework\App\Response\RedirectInterface $_redirect */
        $block->setRefererUrl($this->_redirect->getRefererUrl()); // Set referer url in your block.
    }

And then, the block we can get $block->getRefererUrl()

Khoa TruongDinh
  • 32,054
  • 11
  • 88
  • 155