4

I have to display current server host (in PHP, but it is not very important). I don't know on which host I am. How can I do that without security issue ? If I use $_SERVER['HTTP_HOST'], it comes from client so I can't trust this information (it can be rewritten, I think).

PS: I've read this post : How reliable is HTTP_HOST? but I did not find any response (maybe I did not search correctly...)

Community
  • 1
  • 1
rap-2-h
  • 30,204
  • 37
  • 167
  • 263
  • What are you looking to use the HTTP_HOST value for? Just spitting it back our onto the screen? Inserting it into a DB? Creating links with it? – Jonathan S. Jun 13 '12 at 14:38
  • You can make some header sanitizing in Apache, if needed... – Tisho Jun 13 '12 at 14:40
  • @georgefox: I want to use it for different goals : displaying (I can use JS in this case), generating permanent link, send mail with this host in text, or even store in database, etc. – rap-2-h Jun 13 '12 at 14:44

3 Answers3

5

Use $_SERVER['SERVER_NAME'] for this purpose, from the docs :

The name of the server host under which the current script is executing. If the script is running on a virtual host, this will be the value defined for that virtual host.

ilanco
  • 9,581
  • 4
  • 32
  • 37
  • Ok, but what about aliases ? Will it work ? If my server name is "test.org" and I have some aliases like "test2.org", "test3.org", and my client is logged on "test2.org", $_SERVER['SERVER_NAME'] will be "test.org" ? (I want "test2.org" insteed) – rap-2-h Jun 13 '12 at 14:56
  • @rap-2-h test2.org will be passed as this was the host requested by the client. – Eugene Mayevski 'Callback Jun 13 '12 at 17:22
1

If you're not planning to use it for security or authentication purposes, then $_SERVER['HTTP_HOST'] should be fine. You may have incorrect values for your script kiddie visitors, but your regular users will be using well-behaved browsers.

You won't have any security issues as long as you treat it like you would any other user input. Sanitize it, don't build filenames or execute commands based on it, escape it before you display it, etc.

grossvogel
  • 6,694
  • 1
  • 25
  • 36
  • Ok, thanks, I will think about your analysis. I don't build filenames nor execute commands. I will reconsider the security level I want to implement. – rap-2-h Jun 14 '12 at 08:47
0

You might even give

php_uname('n');

or maybe even

`hostname -f`

(notice the backticks here) a try.

  • Ok, thanks ! According to http://www.php.net/manual/fr/function.php-uname.php#105524 : "The machine that you are running the script may server many different host names so don't use this when building urls", so I can not use it in my case (I have different hosts on my server) – rap-2-h Jun 14 '12 at 08:34
  • Damn, i just re-read your question. In that case only $_SERVER['SERVER_NAME'] remains, i guess. – Hauke Haien Jun 14 '12 at 15:12