PHP Server Variables: 'HTTP_HOST' vs. 'SERVER_NAME'
You've encountered some information suggesting that using any of the $_SERVER variables is unsafe, leading you to question the appropriateness of using $_SERVER['HTTP_HOST'] and $_SERVER['SERVER_NAME']. Let's clarify the situation.
As you've gathered, $_SERVER['SERVER_NAME'] is determined by the web server's configuration, while $_SERVER['HTTP_HOST'] is based on the client's request. This distinction raises the question of which variable to use for reliable link definitions site-wide.
While it may seem logical to use $_SERVER['HTTP_HOST'] for compatibility, Chris Shiflett's article "SERVER_NAME Versus HTTP_HOST" reveals a more complex situation. Apache web servers can be configured to use canonical names, ensuring consistent server names with SERVER_NAME. However, if this configuration is not enforced, relying on HTTP_HOST alone may not be sufficient.
To ensure the integrity of your links, consider these options:
$allowed_hosts = array('foo.example.com', 'bar.example.com'); if (!isset($_SERVER['HTTP_HOST']) || !in_array($_SERVER['HTTP_HOST'], $allowed_hosts)) { header($_SERVER['SERVER_PROTOCOL'].' 400 Bad Request'); exit; }
By evaluating these options and considering the security concerns raised, you can make an informed decision about which approach is most appropriate for your PHP scripts.
The above is the detailed content of $_SERVER[\'HTTP_HOST\'] vs. $_SERVER[\'SERVER_NAME\']: Which Should You Use for Secure Links?. For more information, please follow other related articles on the PHP Chinese website!