$_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME'] in PHP
While working with PHP scripts, it's crucial to understand the differences between $_SERVER['HTTP_HOST'] and $_SERVER['SERVER_NAME'].
Understanding $_SERVER Variables
$_SERVER['SERVER_NAME'] is determined by your web server's configuration, influenced by directives like VirtualHost, ServerName, and UseCanonicalName. In contrast, $_SERVER['HTTP_HOST'] is derived from the client's request.
Which Variable to Use?
To maximize script compatibility, it seems logical to opt for $_SERVER['HTTP_HOST']. However, the situation is slightly more complex. Chris Shiflett's article, "SERVER_NAME Versus HTTP_HOST," highlights that no clear solution exists.
Potential Security Concerns
While $_SERVER['HTTP_HOST'] appears harmless for use in links and forms, it's important to remember that $_SERVER variables can be manipulated by attackers. To mitigate this risk, it's prudent to whitelist allowed host names, as demonstrated in the following code:
$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 adhering to these guidelines, developers can confidently use $_SERVER variables in their PHP scripts while maintaining a secure environment.
The above is the detailed content of When Should You Use $_SERVER[\'HTTP_HOST\'] vs. $_SERVER[\'SERVER_NAME\'] in PHP?. For more information, please follow other related articles on the PHP Chinese website!