Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get .tld from URL via PHP

Tags:

url

php

How to get the .tld from an URL via PHP?

E.g. www.domain.com/site, the PHP should post: tld is: .com.

like image 652
fr3d Avatar asked Aug 24 '16 09:08

fr3d


1 Answers

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'
like image 185
Oleksandr Fediashov Avatar answered Sep 23 '22 22:09

Oleksandr Fediashov