Get the current page url in Magento 2.0
Don't use object manager instance directly in files
With objectManager
$urlInterface = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Framework\UrlInterface');
$urlInterface->getCurrentUrl();
With Factory Method
protected $_urlInterface;
public function __construct(
...
\Magento\Framework\UrlInterface $urlInterface
...
) {
$this->_urlInterface = $urlInterface;
}
public function getUrlInterfaceData()
{
echo $this->_urlInterface->getCurrentUrl();
echo $this->_urlInterface->getUrl();
echo $this->_urlInterface->getUrl('test/test2');
echo $this->_urlInterface->getBaseUrl();
}
Without Object Manager, you can use below line to get current URL
on the templates file
$this->getUrl('*/*/*', ['_current' => true, '_use_rewrite' => true])
The universal solution: works from anywhere, not only from a template:
/** @var \Magento\Framework\UrlInterface $urlInterface */
$urlInterface = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Framework\UrlInterface');
$urlInterface->getCurrentUrl();
From a template you can do it simplier: by using the \Magento\Framework\View\Element\AbstractBlock::getUrl()
method:
$block->getUrl();
An example from the core: https://github.com/magento/magento2/blob/2.0.0/app/code/Magento/Customer/view/frontend/templates/logout.phtml#L14