Get Base Url within ZF2 Controller

Getting the base url of a request in Zend Framework 2 is quite simple. Because you are probably extending the AbstractActionController class, you get some functionality out of the box, including easily accessing the current request. From the request, one can get the URI, which exposes various methods for different parts of the URI. In this case, we need the scheme as well as the host name, as in the below example.

public function indexAction()
    $uri = $this->getRequest()->getUri();
    $baseUrl = sprintf('%s://%s', $uri->getScheme(), $uri->getHost());

That’s all it takes! Thank you for reading.

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *