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.
And why could the HTTP_HOST sometimes be not set?
Are you using PHP-CLI?
HTTP_HOST works only on the browser.
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.
The HTTP_HOST must always be set if you are running on a browser... then there is no need to check... simply,
$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.
I would also set $host to a sensible default (depends on your application) before the 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.
$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!
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.