In Magento 2, You can get Base Url, Current Url, get Media URL, get static page URL and custom URL using Magento\Store\Model\StoreManagerInterface and Magento\Framework\UrlInterface Object.
Using StoreManager Object,
Create PHP file and Passed Dependency injection Magento\Store\Model\StoreManagerInterface,
public function __construct( \Magento\Store\Model\StoreManagerInterface $storeManager ) { $this->storeManager = $storeManager; } public function getStoreManagerData() { return $this->storeManager->getStore(); }
Call in Template file,
<?php $storeManager = $block->getStoreManagerData(); echo $storeManager->getBaseUrl(); Output: http://www.rjesadiya.com/default/ echo $storeManager->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_WEB); Output: http://www.rjesadiya.com/ echo $storeManager->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_DIRECT_LINK); Output: http://www.rjesadiya.com/ echo $storeManager->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA); Output: http://www.rjesadiya.com/pub/media/ echo $storeManager->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_STATIC); Output: http://www.rjesadiya.com/pub/static/version1543556724/ echo $storeManager->getUrl('customer/account/login'); Output: http://www.rjesadiya.com/default/customer/account/login/ For Set Secure Url, echo $storeManager->getUrl('customer/account/login', ['_secure' => true]); Output: https://www.rjesadiya.com/default/customer/account/login/ echo $storeManager->getCurrentUrl(false); Output: http://www.rjesadiya.com/default/training/index/training echo $storeManager->getCurrentUrl(); Output: http://www.rjesadiya.com/default/training/index/training?___from_store=default echo $storeManager->isUrlSecure(); // false if URL is not secure, true if URL is secure
URL Using UrlInterface Object in Plugin and Observer file,
public function __construct( \Magento\Framework\UrlInterface $urlBuilder ) { $this->urlBuilder = $urlBuilder; }
Call In template file,
echo $this->urlBuilder->getCurrentUrl(); Output: http://www.rjesadiya.com/training/index/training echo $this->urlBuilder->getUrl(); Output: http://www.rjesadiya.com/default/ echo $this->urlBuilder->getUrl('customer/account/login'); Output: http://www.rjesadiya.com/default/customer/account/login/ echo $this->urlBuilder->getBaseUrl(); Output: http://www.rjesadiya.com/default/
You can add a Query parameter in URL,
// You can set query parameter using
$url = $this->urlBuilder->setQueryParam(‘query1’, ‘value1’);
if you want to pass multiple query parameter you need to call again above line,
public function getQueryParameter() { $url = $this->urlBuilder->setQueryParam('query1', 'value1'); $url = $this->urlBuilder->setQueryParam('query2', 'value2'); return $url->getUrl('catalogsearch/result/index'); }
echo $block->getQueryParameter();
Output:
http://www.rjesadiya.com/default/catalogsearch/result/index/?query1=value1&query2=value2