Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get baseUrl in ZF2 controller?

In my zf2 controller I want to retrieve the application base URL (for example http://example.com).

I tried the following call but it returns an empty string.

$this->request->getBasePath();

How can I then get the http://example.com part of URL in my controller?

like image 772
Hanmant Avatar asked Sep 13 '12 10:09

Hanmant


2 Answers

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://example.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());
}
like image 153
Andris Avatar answered Nov 10 '22 14:11

Andris


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!

like image 37
Daniel M Avatar answered Nov 10 '22 14:11

Daniel M