title: How to get real host or server name in PHP
body: <p>How can I get real host name by not using $_SERVER['SERVER_NAME'] in PHP? Is there other more reliable way to get it ?  </p>
  
  <p>I have created a function which gets host name from the path to the domain.  </p>
  
  <p>I would like to avoid using $_SERVER['SERVER_NAME'] variable, because it can be faked by sending modified headers in the HTTP request.</p>
  
  <p>This is my current implementation (this works if the path has an actual domain name in it. For instance: /vhosts/website.com/public_html):</p>
  
  <pre><code>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: http://www.in.tv)
   if (strlen($url[0][0]) &gt; 4) {
    $result = str_replace("/", "", $url[0][0]);
    return $result;
   }
   else
    return false;
  }
  </code></pre>
  
  <p>Thanks!</p>