Henk Z Henk Z - 1 year ago 67
PHP Question

Get entered domainname PHP

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, 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));


Answer Source

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: http://stackoverflow.com/a/15498686/575828

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