Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong><em>Note: as pointed out in the comments, this method doesn't actually work in all cases. The reason for this is that some top-level domains do resolve to IP addresses, even if most do not. Therefore it's not possible to detect if a given name is top-level or pseudo-top-level domain name merely by checking if it has an IP address. Unfortunately, this probably means that the only solution is a lookup list, given how inconsistently treated top-level domains are in practice.</em></strong></p> <p><strong><em>I repeat: do not rely on the code below to work for you. I leave it here for educational purposes only.</em></strong></p> <p>There is a way to do this without a lookup list. The list may be unreliable or incomplete, whereas this method is guaranteed to work:</p> <pre><code>&lt;?php function get_domain($url) { $dots = substr_count($url, '.'); $domain = ''; for ($end_pieces = $dots; $end_pieces &gt; 0; $end_pieces--) { $test_domain = end(explode('.', $url, $end_pieces)); if (dns_check_record($test_domain, 'A')) { $domain = $test_domain; break; } } return $domain; } $my_domain = get_domain('www.robknight.org.uk'); echo $my_domain; ?&gt; </code></pre> <p>In this case, it will output 'robknight.org.uk'. It would work equally well for .com, .edu, .com.au, .ly or whatever other top-level domain you're operating on.</p> <p>It works by starting from the right and doing a DNS check on the first thing that looks like it might be a viable domain name. In the example above, it starts with 'org.uk', but discovers that this is not an actual domain name, but is a ccTLD. It then moves on to check 'robknight.org.uk', which <em>is</em> valid, and returns that. If the domain name had been, say, 'www.php.net', it would have started by checking 'php.net', which is a valid domain name, and would have returned that immediately without looping. I should also point out that if no valid domain name is found, an empty string ('') will be returned.</p> <p>This code may be unsuitable for processing a large number of domain names in a short space of time due to the time taken for DNS lookups, but it's perfectly fine for single lookups or code that isn't time-critical.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload