如何获取主机地址?例如,我的网站位于以下位置:http://example.org/index/news/我只想提取http://example.org/。
我询问ZF的功能。我知道$_SERVER['HTTP_HOST'],但我正在寻找一些本地的东西。
来自控制器:
$this->getRequest()->getServer('HTTP_HOST')
这将给你example.org
,剩下的你必须添加到它周围。
接受的答案非常好,但您可能需要记住一些事情。
$this->getRequest();
是一个函数/方法调用,这意味着不需要开销,因为控制器具有受保护的$_request
属性,所以
$this->_request
getRequest
方法只不过是暴露$_request
属性(它是一个公共方法):
public function getRequest()
{
return $this->_request;
}
应该表现得稍微好一点。此外,如果您查找getServer
方法的来源:
public function getServer($key = null, $default = null)
{
if (null === $key) {
return $_SERVER;
}
return (isset($_SERVER[$key])) ? $_SERVER[$key] : $default;
}
在使用该方法时,除了语法糖之外,没有提供默认值是没有意义的
最快的方法永远是
$_SERVER['HTTP_HOST'];
然而,将两个世界中最好的结合起来,最安全(也是最像ZF的方式)的方法是:
$this->_request->getServer('HTTP_HOST', 'localhost');//default to localhost, or whatever you prefer.
你正在寻找的完整代码可能是:
$base = 'http';
if ($this->_request->getServer('HTTPS', 'off') !== 'off')
{
$base .= 's';
}
$base .= '://'.$this->_request->getServer('SERVER_NAME', 'localhost').'/';
在您的情况下,这应该会导致http://expample.org/
请参阅此处以获取SERVER参数的完整列表,它们的含义以及值可能是什么…