Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get real host or server name in PHP

Tags:

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/website.com/public_html):

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]) > 4) {
  $result = str_replace("/", "", $url[0][0]);
  return $result;
 }
 else
  return false;
}

Thanks!

like image 206
minnur Avatar asked Dec 01 '22 06:12

minnur


1 Answers

If you want a server name that can't be set by the client, use $_SERVER['SERVER_NAME']. It is set by the server itself but can also be forged under certain circumstances using a bug, as Gumbo points out and links to in the comments.

like image 170
Pekka Avatar answered Dec 04 '22 11:12

Pekka