Home > OS >  Alternative to $_SERVER['HTTP_HOST']
Alternative to $_SERVER['HTTP_HOST']

Time:11-10

I have read the first comment here which said:

All elements of the $SERVER array whose keys begin with 'HTTP' come from HTTP request headers and are not to be trusted.

As well as this answer which said:

$_SERVER["HTTP_HOST"] is the HTTP Host header, as sent from the client. That makes this header generally unsafe.

They are all saying that $_SERVER['HTTP_HOST'] is not safe, BUT there is only one alternative so far as I can see which is $_SERVER['SERVER_NAME'].

$_SERVER['SERVER_NAME'] is also not safe which is highlighted in the official doc:

Note: Under Apache 2, UseCanonicalName = On and ServerName must be set. Otherwise, this value reflects the hostname supplied by the client, which can be spoofed. It is not safe to rely on this value in security-dependent contexts.

So, my question is that there is really no alternative ( considered safe ) to $_SERVER['HTTP_HOST']? Otherwise, I have to use it anyway even though I know it is not safe because I have no choice...

Edited: My purpose is to get the base URL. And I don't have control because this is in a plugin for users who might misconfigure Apache.

CodePudding user response:

"Safe" is always a relative term. A kitchen knife is not safe to use if you hold it by the blade, but that doesn't mean you should look for alternatives, it means you learn how to handle it safely.

$_SERVER['HTTP_HOST'] is "unsafe" in the sense that it could be controlled by the visitor to the page in some circumstances. If you're distributing a plugin, it's also under the control of any other PHP code running in the same request, since it's a writeable global variable. It is not "unsafe" in the sense that a raptor will attack if you use it.

Like with the kitchen knife, the solution is not to avoid it, it's to handle it correctly. For instance, if you're outputting a link, and don't want a weirdly-formatted value to produce something that's not a proper URL, you can validate the value (check it contains only the characters you'd expect in a hostname) or sanitise it (strip out unexpected characters).

Or, if you're worried about the value changing or not being what the site owner expects, you could have the site owner confirm it during a setup process, and store the result in a config file.

  •  Tags:  
  • php
  • Related