Determining the Correct Host Name Variable for PHP Scripts
When defining links in your PHP scripts, choosing the appropriate variable for the hostname is crucial. Historically, It was believed that $_SERVER['HTTP_HOST'] should be used because it is based on the client's request, while $_SERVER['SERVER_NAME'] is based on your server's config file and can vary.
However, as noted in Chris Shiflett's article "SERVER_NAME Versus HTTP_HOST," there is no definite answer. Only by forcing Apache to use the canonical name can you consistently retrieve the correct server name with SERVER_NAME.
In situations where this is not possible, you can consider implementing a white list approach:
$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; }
This method involves checking the host name against a predefined list of allowed values. If the hostname is not present in the list, an error is returned.
It is important to note that while $_SERVER['HTTP_HOST'] may seem like a more flexible choice, it can be vulnerable to manipulation by malicious actors. This can compromise the security of your application.
Therefore, the best decision depends on your specific requirements and security considerations. If you need a reliable and consistent server name, it may be necessary to enforce canonicalization of hostnames in your server configuration and use $_SERVER['SERVER_NAME']. Alternatively, the white list approach with $_SERVER['HTTP_HOST'] provides a more flexible but potentially less secure option.
The above is the detailed content of $_SERVER[\'HTTP_HOST\'] vs. $_SERVER[\'SERVER_NAME\']: Which is the Right Hostname Variable for PHP?. For more information, please follow other related articles on the PHP Chinese website!