Get .tld from URL via PHP

If you want extract host from string www.domain.com/site, usage of parse_url() is acceptable solution for you.

But if you want extract domain or its parts, you need package that using Public Suffix List. Yes, you can use string functions around parse_url(), but it will produce incorrect results with two level TLDs.

I recommend TLDExtract [note: library has been deprecated in favour of the similar PHP Domain Parser] for domain parsing, here is sample code that show diff:

$extract = new LayerShifter\TLDExtract\Extract();

# For 'http://www.example.com/site'

$url = 'http://www.example.com/site';

parse_url($url, PHP_URL_HOST); // will return www.example.com
end(explode(".", parse_url($url, PHP_URL_HOST))); // will return com

$result = $extract->parse($url);
$result->getFullHost(); // will return 'www.example.com'
$result->getRegistrableDomain(); // will return 'example.com'
$result->getSuffix(); // will return 'com'

# For 'http://www.example.co.uk/site'

$url = 'http://www.example.co.uk/site';

parse_url($url, PHP_URL_HOST); // will return 'www.example.co.uk'
end(explode(".", parse_url($url, PHP_URL_HOST))); // will return uk, not co.uk

$result = $extract->parse($url);
$result->getFullHost(); // will return 'www.example.co.uk'
$result->getRegistrableDomain(); // will return 'example.co.uk'
$result->getSuffix(); // will return 'co.uk'

Use parse_url() function to get host part of the url then explode by . and get last element of an array

Example below:

$url = 'http://www.example.com/site';
echo end(explode(".", parse_url($url, PHP_URL_HOST))); // echos "com"

Before that it would be nice to check if $url is actual URL with filter_var for example

EDIT:

$url =  'http://' . $_SERVER['SERVER_NAME']; 
echo end(explode(".", parse_url($url, PHP_URL_HOST))); 
// echos "com"

The accepted answer doesn't work on .co.uk for example. If your url's all have the same sub-domain OR no sub-domain at all, you can do something like this.

$urls = array(
    'http://domain.com/site/blah/',
    'http://www.domain.com/site/blah/',
    'http://www.domain.audio/site?hithere=1',
    'http://www.domain.co.uk/site?somehing=%2babc',
);
$subdomain = 'www.';
foreach($urls as $url){
    $host = parse_url($url, PHP_URL_HOST);
    $host = str_ireplace($subdomain,'',$host);
    $tld = strstr($host, '.');
    echo "$tld | ";
}

OUTPUT: .com | .com | .audio | .co.uk |


Short answer

$extension = pathinfo($_SERVER['SERVER_NAME'], PATHINFO_EXTENSION);

easy!

Tags:

Php

Url