$_SERVER['HTTP_HOST']
和 $_SERVER['SERVER_NAME']
在 PHP 中有什么区别?
您何时会考虑使用其中一种,为什么?
最佳答案
HTTP_HOST
从 HTTP request header 获得这就是客户端实际用作请求的“目标主机”的内容。 SERVER_NAME
在服务器配置中定义。使用哪一个取决于您需要它的用途。但是,您现在应该意识到,一个是客户端控制的值,因此在业务逻辑中使用可能不可靠,另一个是更可靠的服务器控制的值。但是,您需要确保有问题的网络服务器具有 SERVER_NAME
正确配置。以 Apache HTTPD 为例,这里是 its documentation 的摘录:
If no
ServerName
is specified, then the server attempts to deduce the hostname by performing a reverse lookup on the IP address. If no port is specified in theServerName
, then the server will use the port from the incoming request. For optimal reliability and predictability, you should specify an explicit hostname and port using theServerName
directive.
更新:检查后the answer of Pekka on your question其中包含指向 bobince's answer 的链接PHP 总是会返回 HTTP_HOST
SERVER_NAME
的值,这与我几年前的 PHP 4.x + Apache HTTPD 1.2.x 经验背道而驰,我从我当前在 Windows XP 上的 XAMPP 环境(Apache HTTPD 2.2.1 和 PHP 5.2.8)上吹了一些灰尘,开始它,创建了一个打印这两个值的 PHP 页面,使用 URLConnection
创建了一个 Java 测试应用程序修改Host
标题和测试告诉我确实(错误地)是这种情况。
在第一次怀疑 PHP 并挖掘了一些 PHP bug reports 之后关于这个主题,我了解到问题的根源在于使用的 Web 服务器,它错误地返回了 HTTP Host
标题当SERVER_NAME
被要求。所以我挖了Apache HTTPD bug reports使用 various keywords关于这个主题,我终于找到了 related bug .这种行为是在 Apache HTTPD 1.3 前后引入的。您需要设置 UseCanonicalName
对 on
的指令在 <VirtualHost>
ServerName
的条目在 httpd.conf
(同时查看 the document 底部的警告!)。
<VirtualHost *>
ServerName example.com
UseCanonicalName on
</VirtualHost>
这对我有用。
总结,SERVER_NAME
更可靠,但您依赖服务器配置!
关于php - PHP 中的 HTTP_HOST 和 SERVER_NAME 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2297403/