Michael Ecklund
Michael Ecklund

Reputation: 1256

How can I check for domain.com or sub.domain.com?

I tried $_SERVER['HTTP_HOST'] & $_SERVER['SERVER_NAME'], but they both return sub.domain.com, I want it to check if the URL is sub.domain.com, or just domain.com.

Script is run on sub.domain.com and they BOTH return the same data.

$_SERVER['HTTP_HOST'] returns: sub.domain.com $_SERVER['SERVER_NAME'] returns: sub.domain.com

I wish to obtain only the domain.com portion of the url. Since the script may run on any subdomain name, I am unsure of how to do so since both of the above variables return the same information.

Upvotes: 1

Views: 2756

Answers (3)

Samy Dindane
Samy Dindane

Reputation: 18726

Little dirty hack:

$explodedHost = explode('.', $_SERVER['HTTP_HOST']);
$size         = count($explodedHost);
$domain       = $explodedHost[$size - 2] . '.' . $explodedHost[$size - 1] . 'com';
if ($_SERVER['HTTP_HOST'] == $domain) {
  // you are on domain.com
}

Upvotes: 0

Paul Dessert
Paul Dessert

Reputation: 6389

You can try the function below (found on php.net)

<?php 
function getHost($Address) { 
$parseUrl = parse_url(trim($Address)); 
return trim($parseUrl[host] ? $parseUrl[host] : array_shift(explode('/', $parseUrl[path],     2))); 
} 

getHost("example.com"); // Gives example.com 
getHost("http://example.com"); // Gives example.com 
getHost("www.example.com"); // Gives www.example.com 
getHost("http://example.com/xyz"); // Gives example.com 
?> 

Upvotes: 0

Patrick
Patrick

Reputation: 3440

I would check HTTP_HOST. Usually both are the same, but sometimes SERVER_NAME is set differently. When in doubt, check them both.

'HTTP_HOST'
Contents of the Host: header from the current request, if there is one.

http://php.net/manual/en/reserved.variables.server.php

As for how to check them, you could do a string replace on it for the primary domain name and see if the result string is empty. Anything left would be the subdomain.


As far you're looking for some trivial string operation, here the last two parts:

$yourhost = implode('.', array_slice(explode('.', $_SERVER['HTTP_HOST']), -2));

Upvotes: 4

Related Questions