简体   繁体   English

未定义索引 HTTP_HOST 即使已检查

[英]Undefined index HTTP_HOST even though it is checked

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?如何在 if 语句内的行上获得“未定义索引 HTTP_HOST”? I mean, the index setting is checked before it is used.我的意思是,在使用之前检查索引设置。

And why could the HTTP_HOST sometimes be not set?为什么有时不设置 HTTP_HOST ?

Are you using PHP-CLI?你在使用 PHP-CLI 吗?

HTTP_HOST works only on the browser. HTTP_HOST 仅适用于浏览器。

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 是相同的。

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足够的

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) before the if statement.我还会在 if 语句之前将 $host 设置为合理的默认值(取决于您的应用程序)。 I have a general rule to not introduce a new variable inside a conditional if it's going to be referred to later.我有一个一般规则,如果以后要引用它,不要在条件中引入新变量。

$host = FALSE;    // or $host = ''; etc. depending on how you'll use it later.
if (isset($_SERVER['HTTP_HOST'])) {
  $host = $_SERVER['HTTP_HOST'];
}

When a request is done with an empty host:当使用空主机完成请求时:

GET / HTTP/1.1
Host:

Then isset($_SERVER['HTTP_HOST']) is true!那么 isset($_SERVER['HTTP_HOST']) 为真!

It is better to use empty like:最好使用空如:

$host = '';
if (!empty($_SERVER['HTTP_HOST'])) {
  $host = $_SERVER['HTTP_HOST'];
}

For detailed info take a look here https://shiflett.org/blog/2006/server-name-versus-http-host有关详细信息,请查看此处https://shiflett.org/blog/2006/server-name-versus-http-host

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM