Printing (sub)domain, stripping .com?

Discussion in 'PHP' started by brianj, May 5, 2009.

  1. #1
    Hi, simple question.. I have 10 sub-domains pointing to my index.php file..

    Question: How can I print the keyword of the sub.domain on page?
    ( example: keyword.domain.com )



    Thanks for help,

    Brian
     
    brianj, May 5, 2009 IP
  2. dannywwww

    dannywwww Well-Known Member

    Messages:
    804
    Likes Received:
    18
    Best Answers:
    0
    Trophy Points:
    110
    #2
    Use explode()

    $peices = explode('.', $_SERVER['HTTP_HOST']);
    echo $peices[0];

    will print out the keyword of the sub domain.
     
    dannywwww, May 5, 2009 IP
  3. Steve136

    Steve136 Peon

    Messages:
    240
    Likes Received:
    15
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Hey There,

    dannywwww is correct, explode will do the job perfectly.

    I've made it into a function, to check the HTTP_HOST is set and then split the sub-domain out of it into an array - It will check the element of the array before returning it, else an error.

    
    echo 'Current Sub-Domain is:' . getSubDomain();
    
    function getSubDomain() {
    	if(isset($_SERVER['HTTP_HOST'])) {
    		$subDomain = Array();
    		$subDomain = explode('.', $_SERVER['HTTP_HOST']);
    		if(isset($subDomain[0])) {
    			return $subDomain[0];
    		} else {
    			return 'Failed getting sub-domain for ' . $_SERVER['HTTP_HOST'];
    		}
    	}
    }
    
    PHP:
    Regards,

    Steve
     
    Steve136, May 5, 2009 IP
  4. brianj

    brianj Member

    Messages:
    50
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #4
    Hey, much thanks to both of you.. Danny's snippet just did the job perfectly:)
     
    brianj, May 5, 2009 IP
  5. GreatMetro

    GreatMetro Peon

    Messages:
    117
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Only problem is if someone adds the www before the subdomain:

    www.subdomain.domain.com

    will return "www"

    Here's a better function:

    
    function subDomain($domain) 
    {
    	$host = $_SERVER['HTTP_HOST']; 
    	$parts = explode('.',$host);
    	$where = array_search($domain,$parts);
    	$sub = $parts[$where-1];
    	if ($sub == 'www' || $sub == '') {
                return('No sub-domain');
    	}
    	return ($sub);
    }
    
    $domain = "YOURDOMAIN.COM";
    echo "Subdomain is " . subDomain($domain);
    
    
    PHP:
     
    GreatMetro, May 6, 2009 IP