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.

Community
  • 1
  • 1
Ben
  • 6,026
  • 11
  • 51
  • 72

2 Answers2

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]

Jean-Christophe Meillaud
  • 1,961
  • 1
  • 21
  • 27
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.

Sietse
  • 707
  • 4
  • 10