1

Possible Duplicate:
PHP function to get the subdomain of a URL

Im looking for an efficient way to tell if a subdomain exists within a URL.

The domain name will always be fixed e.g. mydomin.com, however if a subdomain is not set, I need to redirect.

One thought I had is that if there is more than one period (.), a subdomain is set, but im not sure how to implement this.

Many thanks.

EDIT: Sorry for not being too clear. I do not have a current solution, but looking at other posts I can see several examples of how to get the subdomain e.g.

array_shift(explode(".",$_SERVER['HTTP_HOST']));

But i do not want the subdomain, just to check if one exists. The subdomain could be anything.

3
  • 1
    stackoverflow.com/questions/5292937/… Commented Oct 6, 2012 at 10:58
  • 4
    Do you already have an inefficient solution? Usually programmers ask about something efficient when their current solution just doesn't fit the performance requirements. So, what's your current one? Commented Oct 6, 2012 at 11:00
  • How are you doing it currently? Commented Oct 6, 2012 at 11:00

2 Answers 2

1

You can get the hostname with parse_url. Then you break it down with explode():

function hasSubdomain($url) {
    $parsed = parse_url($url);
    $exploded = explode('.', $parsed["host"]);
    return (count($exploded) > 2);
}

On google you can find really easily how to redirect someone.

Sign up to request clarification or add additional context in comments.

3 Comments

What about "someDomainName.co.uk"? I wouldn't say that has a subdomain. But that would return true for this function no?
Just check if count() is higher than 3, instead of 2.
I guess this is the better answer: stackoverflow.com/a/288864/839332 But thanks anyway.
1

I would rather use apache rewrite engine (or any webserver rewrite process) :

# .htaccess file

RewriteCond %{HTTP_HOST} ^yourdomin\.com$
RewriteRule (.*) http://sub.yourdomin.com/$1 [R=301,L]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.