Php – How to get real host or server name in PHP


How can I get real host name by not using $_SERVER['SERVER_NAME'] in PHP? Is there other more reliable way to get it ?

I have created a function which gets host name from the path to the domain.

I would like to avoid using $_SERVER['SERVER_NAME'] variable, because it can be faked by sending modified headers in the HTTP request.

This is my current implementation (this works if the path has an actual domain name in it. For instance: /vhosts/

function getServerName() {
 $path = realpath(__FILE__);
 $url = array();
 preg_match_all("/\/[a-z0-9-]+(\.[a-z0-9-]+)+/i", $path, $url);
 // 4 is minimum requirement for the address (e.g:
 if (strlen($url[0][0]) > 4) {
  $result = str_replace("/", "", $url[0][0]);
  return $result;
  return false;


Best Solution

Edit: as pointed by Gumbo, the original poster probably means HTTP_HOST rather than HOST_NAME. Otherwise, my answer is plain wrong.

The HTTP_HOST variable reflects the domain name that the visitor used to access the site. If doesn't have anything to do with file paths! Its value is conveniently stored in $_SERVER['HTTP_HOST']. Is there any other way to get it? Of course, there're normally several ways to do things. For instance, this works when PHP runs as Apache module.


$request_headers = apache_request_headers();
echo $request_headers['Host'];


The question is: why would anyone want to do such a thing? Why replace a reliable standard method with a quirky workaround that eventually fetches the same piece of data from the same place?

You have the concern that $_SERVER['HTTP_HOST'] is altered by the HTTP request. Of course it is: that's where it comes from. The browser has to specify what site it wants to visit (that's the base of name based virtual hosts) and if it sends a rogue value, well, it just won't reach the site.