$_SERVER[\'HTTP_HOST\'] vs. $_SERVER[\'SERVER_NAME\']: Which Should You Use for Secure Links?

Barbara Streisand
Release: 2024-11-24 21:53:35
Original
320 people have browsed it

$_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME']: Which Should You Use for Secure Links?

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:

  • Enforce Canonical Names: Configure Apache to use canonical names, ensuring that SERVER_NAME always provides the correct server name.
  • Validate Host Name: Use a whitelist to verify that the host name provided in the HTTP_HOST header is valid. Example:
$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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template