Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to get subdomain URL using php

Tags:

url

php

subdomain

Actually I am trying to get the sub-domain URL using php. I write code below:

$sub_url = explode('.', $_SERVER['HTTP_HOST']);
$suburl = $sub_url[0];

For Example: if sub domain URL is like my.example.com the code above is giving me my which is good but if there is no sub domain then my code will return example which is not good.

I want anything before the first dot even www but if there is nothing like if URL is example.com then I want a blank value instead of example.

like image 698
GamesPlay Avatar asked Nov 16 '25 17:11

GamesPlay


2 Answers

Here's a one-liner to get the subdomain:

$subdomain = join('.', explode('.', $_SERVER['HTTP_HOST'], -2))

explode with the limit parameter of -2 will split the string on each dot, ignoring the last two elements. If there are two or fewer elements, it returns an empty array.

join will assemble the resulting array back into a dot delimited string. In case you have multiple subdomains set, e.g. foo.bar.domain.com will return foo.bar.

If there is no subdomain, it will return an empty string.

like image 109
DarthJDG Avatar answered Nov 18 '25 07:11

DarthJDG


I'd assume you can just check the size of the array, assuming it was always the same size, if it was any larger you may run into problems.

$sub_url = explode('.', $_SERVER['HTTP_HOST']);

if (sizeof($sub_url) > 2) {
    $suburl = $sub_url[0];
} else {
    $suburl = null;
}
like image 39
Byron Filer Avatar answered Nov 18 '25 07:11

Byron Filer