简体   繁体   English

尝试使用php获取子域URL

[英]Trying to get subdomain URL using php

Actually I am trying to get the sub-domain URL using php. 实际上,我正在尝试使用php获取子域URL。 I write code below: 我在下面写代码:

$sub_url = explode('.', $_SERVER['HTTP_HOST']);
$suburl = $sub_url[0];

For Example: if sub domain URL is like my.example.com the code above is giving me my which is good but if there is no sub domain then my code will return example which is not good. 例如:如果子域URL类似于my.example.com则上面的代码会给我my很好,但是如果没有子域,则我的代码将返回不好的example

I want anything before the first dot even www but if there is nothing like if URL is example.com then I want a blank value instead of example . 我想要第一个点之前的任何东西,甚至www但是如果没有类似URL是example.com那么我想要一个空白值而不是example

Here's a one-liner to get the subdomain: 这是获取子域的一种方法:

$subdomain = join('.', explode('.', $_SERVER['HTTP_HOST'], -2))

explode with the limit parameter of -2 will split the string on each dot, ignoring the last two elements. 使用limit参数-2 explode会在每个点上拆分字符串,而忽略最后两个元素。 If there are two or fewer elements, it returns an empty array. 如果有两个或更少的元素,则返回一个空数组。

join will assemble the resulting array back into a dot delimited string. join会将结果数组重新组合成点分隔的字符串。 In case you have multiple subdomains set, eg foo.bar.domain.com will return foo.bar . 如果您设置了多个子域,例如foo.bar.domain.com将返回foo.bar

If there is no subdomain, it will return an empty string. 如果没有子域,它将返回一个空字符串。

I'd assume you can just check the size of the array, assuming it was always the same size, if it was any larger you may run into problems. 我假设您可以检查数组的大小,假设它始终是相同的大小,如果更大,则可能会遇到问题。

$sub_url = explode('.', $_SERVER['HTTP_HOST']);

if (sizeof($sub_url) > 2) {
    $suburl = $sub_url[0];
} else {
    $suburl = null;
}

You should notice that, there are also websites with second level domains, for example co.uk , com.cn . 您应该注意到,还有一些具有二级域名的网站,例如co.ukcom.cn If you can make sure, that your code will not be used on such website, you can simple use the answer of DarthJDG or check count($sub_url) > 2 . 如果可以确保不会在此类网站上使用您的代码,则可以简单地使用DarthJDG的答案或检查count($sub_url) > 2 But if not, you need to check the domain name. 但是,如果没有,则需要检查域名。

$secondLevelDomainsList = str_getcsv(file_get_contents('https://raw.github.com/gavingmiller/second-level-domains/master/SLDs.csv'), PHP_EOL);
foreach($secondLevelDomainsList as &$item) {
    list($tld, $stld) = str_getcsv($item, ",");
    $item = $stld;
}    
$urlParts = explode('.', $url);    
$challenger = '.' . join('.', array_slice($urlParts, -2, 2, true));    
$length = in_array($challenger, $secondLevelDomainsList) ? -3 : -2;    
$subDomainName = join('.', array_slice($urlParts, 0, $length, true));

The list of second level domains in format of CSV from gavingmiller/second-level-domains github repository is used for the test, if the domain is a second level domain. 如果该域是第二级域,则使用来自gavingmiller / second-domain-domains github存储库的CSV格式的第二级域列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM