Undefined index HTTP_HOST even though it is checked

前端 未结 5 2267
栀梦
栀梦 2021-02-18 13:17

Here\'s the code:

if (isset($_SERVER[\'HTTP_HOST\']) === TRUE) {
  $host = $_SERVER[\'HTTP_HOST\'];
}

How is it possible to get an \"Undefined

相关标签:
5条回答
  • 2021-02-18 13:59

    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

    0 讨论(0)
  • 2021-02-18 14:02

    Are you using PHP-CLI?

    HTTP_HOST works only on the browser.

    0 讨论(0)
  • 2021-02-18 14:15

    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.

    0 讨论(0)
  • 2021-02-18 14:18

    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

    0 讨论(0)
  • 2021-02-18 14:20

    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'];
    }
    
    0 讨论(0)
提交回复
热议问题