The problem I find using filter_var($url, FILTER_VALIDATE_URL) is that it returns true when $url = "http://x";
No TLD is required. How I can solve this so a TLD is required?
For TLD validation you need library that operates with Public Suffix List. Here are two diffent solutions for you.
First is TLDDatabase, technicaly it's only actual database of TLDs.
$store = new LayerShifter\TLDDatabase\Store();
$store->isICCAN('com'); // returns true
$store->isICCAN('co.uk'); // returns true
$store->isICCAN('example'); // returns false
If you need more intelligent solution, I recomend TLDExtract. It's domain parser that you can use as validator.
$extract = new LayerShifter\TLDExtract\Extract();
$extract->setExtractionMode(Extract::MODE_ALLOW_ICCAN);
# For domain 'shop.github.com'
$result = $extract->parse('shop.github.com');
$result->getRegistrableDomain(); // will return 'github.com'
$result->getSuffix(); // will return 'com'
# For domain 'shop.github.co.uk'
$result = $extract->parse('http://shop.github.co.uk');
$result->getRegistrableDomain(); // will return 'github.co.uk'
$result->getSuffix(); // will return 'co.uk'
# For domain 'example.example'
$result = $extract->parse('https://example.example');
$result->getRegistrableDomain(); // will return NULL
$result->getSuffix(); // will return NULL
# For domain 'localhost'
$result = $extract->parse('localhost');
$result->getRegistrableDomain(); // will return NULL
$result->getSuffix(); // will return NULL
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With