php 未定义索引 HTTP_HOST 即使已检查
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12347048/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Undefined index HTTP_HOST even though it is checked
提问by donk
Here's the code:
这是代码:
if (isset($_SERVER['HTTP_HOST']) === TRUE) {
$host = $_SERVER['HTTP_HOST'];
}
How is it possible to get an "Undefined index HTTP_HOST" on the line inside the if statement? I mean, the index setting is checked before it is used.
如何在 if 语句内的行上获得“未定义索引 HTTP_HOST”?我的意思是,在使用之前检查索引设置。
And why could the HTTP_HOST sometimes be not set?
为什么有时不设置 HTTP_HOST ?
回答by Adil
Are you using PHP-CLI?
你在使用 PHP-CLI 吗?
HTTP_HOST works only on the browser.
HTTP_HOST 仅适用于浏览器。
回答by Sujit Agarwal
The HTTP_HOST must always be set if you are running on a browser... then there is no need to check... simply,
如果您在浏览器上运行,则必须始终设置 HTTP_HOST ......那么就不需要检查......简单地,
$host = $_SERVER['HTTP_HOST'];
is enough
足够
回答by Luke Mills
I would normally omit the === TRUE, as it's not needed here because isset()returns a boolean, but that shouldn't stop your code from working.
我通常会省略=== TRUE, 因为这里不需要它,因为isset()返回一个布尔值,但这不应阻止您的代码工作。
I would also set $host to a sensible default (depends on your application) beforethe if statement. I have a general rule to not introduce a new variable inside a conditional if it's going to be referred to later.
我还会在 if 语句之前将 $host 设置为合理的默认值(取决于您的应用程序)。我有一个一般规则,如果以后要引用它,不要在条件中引入新变量。
$host = FALSE; // or $host = ''; etc. depending on how you'll use it later.
if (isset($_SERVER['HTTP_HOST'])) {
$host = $_SERVER['HTTP_HOST'];
}
回答by Zeru Giran
An bad implemented browser can omit send que host header information, try this example:
一个错误实现的浏览器可以省略发送队列主机头信息,试试这个例子:
telnet myphpserver.com 80
> GET / <enter><enter>
in this case $_SERVER['HTTP_HOST'] not have assigned value, in this case u can use $_SERVER['SERVER_NAME'] but only if $_SERVER['HTTP_HOST'] is empty, because no is the same.
在这种情况下 $_SERVER['HTTP_HOST'] 没有赋值,在这种情况下你可以使用 $_SERVER['SERVER_NAME'] 但前提是 $_SERVER['HTTP_HOST'] 为空,因为 no 是相同的。

