开发者

PHP - allow domains, not subdomains

开发者 https://www.devze.com 2023-04-03 23:19 出处:网络
I would appreciate any help that can be provided with this matter. I am creating a registration form, one field is for the users domain which I will verify is valid withFILTER_VALIDATE_URL and that i

I would appreciate any help that can be provided with this matter.

I am creating a registration form, one field is for the users domain which I will verify is valid with FILTER_VALIDATE_URL and that it exists with dns_check_record.

However a problem I'm having is that using these two methods will also allow subdomains to be submitted to the form which I don't want.

Does anyone know a way to allow domains but not subdomains?

I've tested the following function, from http://syntax.cwarn23.net/PHP/Strip_URL_to_Domain:

开发者_JAVA技巧
function domain($domainb)
{
$bits = explode('/', $domainb);
if ($bits[0]=='http:' || $bits[0]=='https:')
    {
    $domainb= $bits[2];
    } else {
    $domainb= $bits[0];
    }
unset($bits);
$bits = explode('.', $domainb);
$idz=count($bits);
$idz-=3;
if (strlen($bits[($idz+2)])==2) {
$url=$bits[$idz].'.'.$bits[($idz+1)].'.'.$bits[($idz+2)];
} else if (strlen($bits[($idz+2)])==0) {
$url=$bits[($idz)].'.'.$bits[($idz+1)];
} else {
$url=$bits[($idz+1)].'.'.$bits[($idz+2)];
}
return $url;

However this isn't perfect as any domains such as www.domain.uk.com will appear as uk.com (I know not a common domain extension).

Does anyone know a method better than the above function?


As pointed by Micheal Mior, you have to check for .co.uk, .com.br and many others.

Some browser vendors are maintaining a list of such non-TLD that are effectively TLD: http://publicsuffix.org/. The list is quite huge.

There is a library here that uses this effective TLD list to implement the function you are looking for (download are here). (Found via https://wiki.mozilla.org/Gecko:Effective_TLD_Service.)


Combine them.

dns_check_record will fail on '.co.uk', so you can split your string on the dots, check the domain you get when you combine the last two parts, and if that fails, use a third part too, if any.

You will do a double check for invalid domains, but I assume that won't be an issue.


first you could use parse_url() to get only the host name: http://www.stackoverflow.com -> $url['host'] = 'www.stackoverflow.com'

Second you could count the amount of points in the hostname: explode() --> count() or substr_count()

Has the host more than 1 point a subdomain could be exist.

Now you could use the solution mentioned by GolezTrol or arnaud576875.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号