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,
$parsedUrl = parse_url($url);
$host = explode('.', $parsedUrl['host']);
$subdomain = $host;
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
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.