In my zf2 controller I want to retrieve the application base URL (for example http://domain.com
).
I tried the following call but it returns an empty string.
$this->request->getBasePath();
How can I then get the http://domain.com
part of URL in my controller?
I know this is not the prettiest way of doing it but, hey, it works:
public function indexAction()
{
$uri = $this->getRequest()->getUri();
$scheme = $uri->getScheme();
$host = $uri->getHost();
$base = sprintf('%s://%s', $scheme, $host);
// $base would be http://domain.com
}
Or if you don't mind shortening everything you could do it in two lines:
public function indexAction()
{
$uri = $this->getRequest()->getUri();
$base = sprintf('%s://%s', $uri->getScheme(), $uri->getHost());
}
I'm not sure if there's a native way but you can use the Uri
instance from Request
.
You can take this snippet as a workaround until you've found a better solution:
$basePath = $this->getRequest()->getBasePath();
$uri = new \Zend\Uri\Uri($this->getRequest()->getUri());
$uri->setPath($basePath);
$uri->setQuery(array());
$uri->setFragment('');
$baseUrl = $uri->getScheme() . '://' . $uri->getHost() . '/' . $uri->getPath();
This works in the controller context. Note that in line 2, the Uri instance from the request is cloned in order not to modify the request's uri instance directly (to avoid side-effects).
I'm not happy with this solution but at least, it is one.
// Edit: Forgot to add the path, fixed!