How to Get sub domain name from domain name

By | September 8, 2016

Get sub domain name from domain name using php

In some cases we would like to know where the request made from exactly. When there are many domains like test.abc.com, live.abc.com, anothertest.abc.com, etc. In this case if we check the host domain for request all will result in abc.com. To get sub domain name from domain name we can use the following code,

First we need to get the main domain url. And then  use php parse_url() function. The parse_url() function parses a URL and returns an associative array containing any of the various components of the URL that are present.

The returned array contains the following keys depends on the url,
Potential keys within this array are:

scheme – e.g. http
host
port
user
pass
path
query – after the question mark ?
fragment – after the hashmark #
In the above case the host key will have en.example.com. Now by using the php explode function we can get the subdomain name.

🔥0

Leave a Reply