1

I used to have my website into a domain like : www.mydomain.com
But now i've created a subdomain 'test' : www.test.mydomain.com and i moved the whole project files there.

So far so good, the problem is that on my php libraries where i call db connection etc, i use the $_SERVER['DOCUMENT_ROOT'] which gives me the URL without the subdomain , e.x.

$file = $_SERVER['DOCUMENT_ROOT'];//gives me www.mydomain.com 

But i need to get the root with the subdomain, like : www.test.mydomain.com

I dont want to make a trick like to split the url and add the subdomain thing.

Any help would be appreciated.

Theo Itzaris
  • 4,321
  • 3
  • 37
  • 68
  • Might be duplicate http://stackoverflow.com/questions/5292937/php-function-to-get-the-subdomain-of-a-url – Paresh Gami Feb 27 '16 at 14:14
  • `$_SERVER['DOCUMENT_ROOT']` doesn't get any **URL**. It get the **absolute path** of current site document root. To obtain current host you have to use `$_SERVER['HTTP_HOST']` – fusion3k Feb 27 '16 at 14:14

3 Answers3

2

You can try both:

$_SERVER["SERVER_NAME"]

$_SERVER['HTTP_HOST']

Both will return the domain with the subdomain.


$_SERVER["SERVER_NAME"]

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.

$_SERVER['HTTP_HOST']

Contents of the Host: header from the current request, if there is one.

You can read up on the difference between $_SERVER["SERVER_NAME"] and $_SERVER['HTTP_HOST'] at HTTP_HOST vs. SERVER_NAME.

$_SERVER['DOCUMENT_ROOT'] will not work as stated in documentation

The document root directory under which the current script is executing, as defined in the server's configuration file.

More information on $_SERVER at http://php.net/manual/en/reserved.variables.server.php.

Community
  • 1
  • 1
Panda
  • 6,955
  • 6
  • 40
  • 55
2

$_SERVER['DOCUMENT_ROOT'] does not contain the server name! It contains - as the name says - the DOCUMENT_ROOT. This is the directory where the filesystem starts that your webserver serves.

You should try $_SERVER['SERVER_NAME'] instead. This should work if your virtual server setup is correct.

blafasel
  • 1,091
  • 14
  • 25
0

Finally, after two hours searching , I spoke to the system admin and he cleared that he actually created an alias domain which it actually reacts as : www.test.mydomain.com.

I guess that is why i get the www.mydomain.com without the subdomain when i call $_SERVER['DOCUMENT_ROOT'].

Thanks, case closed.

Theo Itzaris
  • 4,321
  • 3
  • 37
  • 68