Search code examples
phphttprequesturipsr-7

How to read the host name from a request URI in PHP?


For the router, I wanted to get the host name from the URI upon a server request. I know that I need to read it from the $_SERVER variable. But it seems that in the $_SERVER array there are multiple entries (at least two) for the host name.

Could you please tell me which value should I choose to read - the most reliable one?

For example, when I have an URI like this:

http://local.mvc/mycontroller/myaction

the $_SERVER array will have:

[HTTP_HOST] => local.mvc
[SERVER_NAME] => local.mvc

I need to obtain the value local.mvc.

Thank you for your time.


Solution

  • SERVER_NAME is the name assigned to the given server in its configuration (be it i.e. apache.conf file and its ServerName directive or similar for other software), while HTTP_HOST value is obtained from the headers of HTTP request that comes from client (web browser usually). These two might differ if your server servers multiple domains (like shared server / virtual server hosting). Depending on the use case you may want to use either of these, however HTTP_HOST seems like better choice as it is always tells what user wanted to reach.