0

I want to echo the entered domain name, without the addition of http://www. and I want to split the TLD from the domain.

How can I display this and what is stable solution?

I currenty have this, but that is displaying including www. and I do not know if this is a stable solution or to split the TLD.

<?php echo "{$_SERVER['HTTP_HOST']}\n"; ?>

EDIT using parse_url():

<?php $url = "{$_SERVER['HTTP_HOST']}";

var_dump(parse_url($url));
var_dump(parse_url($url, PHP_URL_SCHEME));
var_dump(parse_url($url, PHP_URL_USER));
var_dump(parse_url($url, PHP_URL_PASS));
var_dump(parse_url($url, PHP_URL_HOST));
var_dump(parse_url($url, PHP_URL_PORT));
var_dump(parse_url($url, PHP_URL_PATH));
var_dump(parse_url($url, PHP_URL_QUERY));
var_dump(parse_url($url, PHP_URL_FRAGMENT));

?>
JGeer
  • 1,768
  • 1
  • 31
  • 75
  • look at parse_url function – Robert Aug 29 '16 at 09:55
  • 1
    Possible duplicate of [How to get the domain name without www, subdomain, and com/net/org/etc](http://stackoverflow.com/questions/13495828/how-to-get-the-domain-name-without-www-subdomain-and-com-net-org-etc) – Robert Aug 29 '16 at 09:57

1 Answers1

1

Check out parse_url(), which can do the split you want.

You might want to do a substr to get rid of the www. After parsing.

Actually, HTTP_HOST is just the domain name, so...

$domain = preg_replace("/^(www\.)?(.*)$/", '$2', $_SERVER['HTTP_HOST']);

This can be manipulated by attackers in certain circumstances, so make sure you escape it with htmlentities($domain, ENT_QUOTES); when you echo it to the page.

TLD can be extracted with the following when dealing with .example or .com:

$tld = preg_replace("/^.*\.(.*)$/", '$1', $_SERVER['HTTP_HOST']);

If dealing with .co.in or .co.uk then see this answer from the question that @Robert linked to: https://stackoverflow.com/a/15498686/575828

Again, don't forget to escape when printing it out to the page

Community
  • 1
  • 1
jedifans
  • 2,287
  • 1
  • 13
  • 9
  • Thanks! I tried that, but I can not get it right. See my edit what I tried. But I can not split the TLD and also can not get rid of the www. Can you help me with this? – JGeer Aug 29 '16 at 10:12
  • Thanks!! I tried the following code, but I do not get a respons. What am I missing? `` – JGeer Aug 29 '16 at 10:59
  • 1
    Sorry I have updated the preg_replace replacement syntax, which uses $ instead of \ – jedifans Aug 29 '16 at 11:08
  • Great, that works perfect!! The only thing I have is, how can I split the TLD? This so that I can display the TLD inside a `` – JGeer Aug 29 '16 at 11:22
  • Added tld extraction – jedifans Aug 29 '16 at 12:20