Undefined index HTTP_HOST even though it is checked

前端 未结 5 2272
栀梦
栀梦 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 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'];
    }
    

提交回复
热议问题