0

How can I get the host address? For example, my site is located here: http://example.org/index/news/ and I want to extract only http://example.org/.

I ask about ZF function. I know about $_SERVER['HTTP_HOST'] but I'm looking for something native.

Paweł Zegardło
  • 298
  • 3
  • 10

2 Answers2

5

From a controller:

$this->getRequest()->getServer('HTTP_HOST')

that'll give you example.org, the rest you'll have to add around it.

Tim Fountain
  • 33,093
  • 5
  • 41
  • 69
2

The accepted answer is perfectly fine, but a few things you might want to keep in mind.

$this->getRequest();

is a function/method call, which means overhead that isn't necessairy, since controllers have a protected $_request property, so

$this->_request

the getRequest method is does little more than exposing the $_request property (it's a public method):

public function getRequest()
{
    return $this->_request;
}

should be slightly more performant. Also, if you look a the source for the getServer method:

public function getServer($key = null, $default = null)
{
    if (null === $key) {
        return $_SERVER;
    }

    return (isset($_SERVER[$key])) ? $_SERVER[$key] : $default;
}

There really is no point in using the method without supplying a default value, other than syntactic sugar.
The quickest way will always be

$_SERVER['HTTP_HOST'];

However, combining the best of both worlds, the safest (and most ZF-like way) would be:

$this->_request->getServer('HTTP_HOST', 'localhost');//default to localhost, or whatever you prefer.

The full code you're looking for might be:

$base = 'http';
if ($this->_request->getServer('HTTPS', 'off') !== 'off')
{
    $base .= 's';
}
$base .= '://'.$this->_request->getServer('SERVER_NAME', 'localhost').'/';

Which, in your case, should result in http://expample.org/.
see here for a full list of SERVER params you can get, what they mean and what the values might be...

Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149