Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/256.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP函数获取URL的子域_Php_Subdomain - Fatal编程技术网

PHP函数获取URL的子域

PHP函数获取URL的子域,php,subdomain,Php,Subdomain,PHP中是否有获取子域名称的函数 在以下示例中,我希望得到URL的“en”部分: en.example.com 如果您只想要第一节课之前的内容: list($sub) = explode('.', 'en.example.com', 2); 使用该功能 $url = 'http://en.example.com'; $parsedUrl = parse_url($url); $host = explode('.', $parsedUrl['host']); $subdomain =

PHP中是否有获取子域名称的函数

在以下示例中,我希望得到URL的“en”部分:

en.example.com

如果您只想要第一节课之前的内容:

list($sub) = explode('.', 'en.example.com', 2);


使用该功能

$url = 'http://en.example.com';

$parsedUrl = parse_url($url);

$host = explode('.', $parsedUrl['host']);

$subdomain = $host[0];
echo $subdomain;
用于多个子域

$url = 'http://usa.en.example.com';

$parsedUrl = parse_url($url);

$host = explode('.', $parsedUrl['host']);

$subdomains = array_slice($host, 0, count($host) - 2 );
print_r($subdomains);

以下是一个单线解决方案:

array_shift((explode('.', $_SERVER['HTTP_HOST'])));
或者用你的例子:

array_shift((explode('.', 'en.example.com')));
编辑:通过添加双括号修复了“只能通过引用传递变量”


编辑2:从开始,您只需执行以下操作:

explode('.', 'en.example.com')[0];

您可以先获取域名(例如sub.example.com=>example.co.uk),然后使用strstr获取子域

$testArray = array(
    'sub1.sub2.example.co.uk',
    'sub1.example.com',
    'example.com',
    'sub1.sub2.sub3.example.co.uk',
    'sub1.sub2.sub3.example.com',
    'sub1.sub2.example.com'
);

foreach($testArray as $k => $v)
{
    echo $k." => ".extract_subdomains($v)."\n";
}

function extract_domain($domain)
{
    if(preg_match("/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i", $domain, $matches))
    {
        return $matches['domain'];
    } else {
        return $domain;
    }
}

function extract_subdomains($domain)
{
    $subdomains = $domain;
    $domain = extract_domain($subdomains);

    $subdomains = rtrim(strstr($subdomains, $domain, true), '.');

    return $subdomains;
}

我发现最好的简短解决方案是

array_shift(explode(".",$_SERVER['HTTP_HOST']));

最简单、最快的解决方案

$sSubDomain = str_replace('.example.com','',$_SERVER['HTTP_HOST']);

我知道我比赛真的迟到了,但事情是这样的

我所做的是取HTTP_HOST server变量(
$\u server['HTTP_HOST']
)和域中的字母数(因此对于
example.com
它将是11)

然后我使用
substr
函数来获取子域。是的

$numberOfLettersInSubdomain = strlen($_SERVER['HTTP_HOST'])-12
$subdomain = substr($_SERVER['HTTP_HOST'], $numberOfLettersInSubdomain);
我将子字符串从11改为12,因为第二个参数的子字符串从1开始。因此,现在如果您进入test.example.com,
$subdomain
的值将是
test


这比使用
explode
要好,因为如果子域中有
,则不会将其切断。

如果使用drupal 7

这将帮助您:

global $base_path;
global $base_root;  
$fulldomain = parse_url($base_root);    
$splitdomain = explode(".", $fulldomain['host']);
$subdomain = $splitdomain[0];

对于那些获得“错误:严格标准:只能通过引用传递变量”的人 这样使用:

$env=(explode(“.”,$\u服务器['HTTP\u主机]);
$env=数组移位($env)

$host=$\u服务器['HTTP\u主机'];
预匹配(“/[^\.\/]+\.[^\.\/]+$/”,$host,$MATCHS);
$domain=$matches[0];
$url=explode($domain,$host);
$subdomain=str_replace('.','.$url[0]);
回显“子域:”.$subdomain.
; 回显“域:”.$domain.“
”;
在PHP5.3中,您可以使用strstrstr()true参数

echo strstr($_SERVER["HTTP_HOST"], '.', true); //prints en
试试这个

$domain = 'en.example.com';
$tmp = explode('.', $domain);
$subdomain = current($tmp);
echo($subdomain);     // echo "en"
简单地… 只需阅读$match[1]

工作示例 它与此URL列表完美配合

$url = array(
    'http://www.domain.com', // www
    'http://domain.com', // --nothing--
    'https://domain.com', // --nothing--
    'www.domain.com', // www
    'domain.com', // --nothing--
    'www.domain.com/some/path', // www
    'http://sub.domain.com/domain.com', // sub
    'опубликованному.значения.ua', // опубликованному ;)
    'значения.ua', // --nothing--
    'http://sub-domain.domain.net/domain.net', // sub-domain
    'sub-domain.third-Level_DomaIN.domain.uk.co/domain.net' // sub-domain
);

foreach ($url as $u) {
    preg_match('/(?:http[s]*\:\/\/)*(.*?)\.(?=[^\/]*\..{2,5})/i', $u, $match);
    var_dump($match);
}

由于域后缀的唯一可靠来源是域注册器,没有它们的知识,您无法找到子域。 有一个包含所有域后缀的列表。此网站还链接到一个PHP库:

请在下面找到一个例子。我还为en.test.co.uk添加了示例,这是一个带有多后缀(co.uk)的域


如前一个问题所示:

没有真正的100%动态解决方案-我也一直在尝试解决这个问题,由于不同的域扩展(DTL),如果不实际解析所有这些扩展并每次检查它们,这项任务将非常困难:

.com vs.co.uk vs.org.uk

最可靠的选择是定义一个常数(或数据库条目等),用于存储实际域名,并使用
substr()

现在,如果您在
http://test.mymaindomain.co.uk
它将为您提供
测试
或者如果您有多个子域级别
http://another.test.mymaindomain.co.uk
您将获得另一个
。测试
——当然,除非您更新

我希望这能有所帮助。

很简单


reset(explode(“.”,$\u SERVER['HTTP\u HOST'))

这是我的解决方案,它适用于最常见的域,您可以根据需要安装扩展阵列:

$SubDomain = explode('.', explode('|ext|', str_replace(array('.com', '.net', '.org'), '|ext|',$_SERVER['HTTP_HOST']))[0]);

使用正则表达式、字符串函数、parse_url()或它们的组合并不是真正的解决方案。只需使用domain
test.en.example.co.uk
测试任何建议的解决方案,就不会有任何正确的结果

正确的解决方案是使用解析域的包。我推荐,以下是示例代码:

$extract = new LayerShifter\TLDExtract\Extract();

$result = $extract->parse('test.en.example.co.uk');
$result->getSubdomain(); // will return (string) 'test.en'
$result->getSubdomains(); // will return (array) ['test', 'en']
$result->getHostname(); // will return (string) 'example'
$result->getSuffix(); // will return (string) 'co.uk'
你也可以用这个

echo substr($_SERVER['HTTP_HOST'], 0, strrpos($_SERVER['HTTP_HOST'], '.', -5));

我在做这样的事情

$url = https://en.example.com

$splitedBySlash = explode('/', $url);
$splitedByDot = explode('.', $splitedBySlash[2]);

$subdomain = $splitedByDot[0];

PHP7.0:使用explode函数并创建所有结果的列表

list($subdomain,$host) = explode('.', $_SERVER["SERVER_NAME"]);
示例:sub.domain.com

结果:分

echo $host;

结果:域

我们使用此函数处理多个子域,并且多tld还处理ip和本地主机

function analyse_host($_host)
    {
        $my_host   = explode('.', $_host);
        $my_result = ['subdomain' => null, 'root' => null, 'tld' => null];

        // if host is ip, only set as root
        if(filter_var($_host, FILTER_VALIDATE_IP))
        {
            // something like 127.0.0.5
            $my_result['root'] = $_host;
        }
        elseif(count($my_host) === 1)
        {
            // something like localhost
            $my_result['root'] = $_host;
        }
        elseif(count($my_host) === 2)
        {
            // like jibres.com
            $my_result['root'] = $my_host[0];
            $my_result['tld']  = $my_host[1];
        }
        elseif(count($my_host) >= 3)
        {
            // some conditons like
            // ermile.ac.ir
            // ermile.jibres.com
            // ermile.jibres.ac.ir
            // a.ermile.jibres.ac.ir

            // get last one as tld
            $my_result['tld']  = end($my_host);
            array_pop($my_host);

            // check last one after remove is probably tld or not
            $known_tld    = ['com', 'org', 'net', 'gov', 'co', 'ac', 'id', 'sch', 'biz'];
            $probably_tld = end($my_host);
            if(in_array($probably_tld, $known_tld))
            {
                $my_result['tld'] = $probably_tld. '.'. $my_result['tld'];
                array_pop($my_host);
            }

            $my_result['root'] = end($my_host);
            array_pop($my_host);

            // all remain is subdomain
            if(count($my_host) > 0)
            {
                $my_result['subdomain'] = implode('.', $my_host);
            }
        }

        return $my_result;
    }
假设当前url=sub.example.com

$host=array_reverse(分解('.',$服务器['SERVER_NAME']); 如果(计数($host)>=3){ echo“主域为=“.$host[1]”、“$host[0]”和子域为=“.$host[2]”; //主域为=example.com,子域为=sub }否则{ echo“主域为”“..host[1]”.“..host[0]”.“&未找到子域”; //“主域为=example.com&未找到子域”; }
您是否有一个URL作为字符串存储在变量中,或者此URL来自何处?背景是什么?请详细说明。您不能使用执行类似于
(^ |:://)(.*)\.
的操作并捕获
*
的正则表达式吗?我对php和regex都很差劲,但我想到了这一点。在
en.foo.bar.example.com
en.example.co.uk
?解析url也有帮助有更好的方法自动检测当前主机(如
$\u服务器['HTTP\u主机]
),然后依靠可伪造的引用头,假设这就是答案背后的总体思路。对,我使用的是一段旧代码。然而,这个例子仍然存在。这并不是问题的根源。综上所述,依赖$_服务器['HTTP_HOST']可能没有效果,因为它可能没有设置。如果在开始时有一个协议处理程序,例如HTTP://、https://、ftp://,等等,该怎么办?;)@Jared,他要分析的字符串中没有协议。。。但是如果有,我会使用
parse_url()
来提取主机。因此,我们提供了两种方法,它们适用于不同的上下文。主要是,我很高兴
<?php

require_once 'vendor/autoload.php';

$pslManager = new Pdp\PublicSuffixListManager();
$parser = new Pdp\Parser($pslManager->getList());
$host = 'http://en.example.com';
$url = $parser->parseUrl($host);

echo $url->host->subdomain;


$host = 'http://en.test.co.uk';
$url = $parser->parseUrl($host);

echo $url->host->subdomain;
$domain = 'sub.dev.example.com';
$tmp = explode('.', $domain); // split into parts
$subdomain = current($tmp);
print($subdomain);     // prints "sub"
defined("DOMAIN")
    || define("DOMAIN", 'mymaindomain.co.uk');



function getSubDomain() {

    if (empty($_SERVER['SERVER_NAME'])) {

        return null;

    }

    $subDomain = substr($_SERVER['SERVER_NAME'], 0, -(strlen(DOMAIN)));

    if (empty($subDomain)) {

        return null;

    }

    return rtrim($subDomain, '.');

}
$SubDomain = explode('.', explode('|ext|', str_replace(array('.com', '.net', '.org'), '|ext|',$_SERVER['HTTP_HOST']))[0]);
$extract = new LayerShifter\TLDExtract\Extract();

$result = $extract->parse('test.en.example.co.uk');
$result->getSubdomain(); // will return (string) 'test.en'
$result->getSubdomains(); // will return (array) ['test', 'en']
$result->getHostname(); // will return (string) 'example'
$result->getSuffix(); // will return (string) 'co.uk'
echo substr($_SERVER['HTTP_HOST'], 0, strrpos($_SERVER['HTTP_HOST'], '.', -5));
$url = https://en.example.com

$splitedBySlash = explode('/', $url);
$splitedByDot = explode('.', $splitedBySlash[2]);

$subdomain = $splitedByDot[0];
list($subdomain,$host) = explode('.', $_SERVER["SERVER_NAME"]);
echo $subdomain; 
echo $host;
function analyse_host($_host)
    {
        $my_host   = explode('.', $_host);
        $my_result = ['subdomain' => null, 'root' => null, 'tld' => null];

        // if host is ip, only set as root
        if(filter_var($_host, FILTER_VALIDATE_IP))
        {
            // something like 127.0.0.5
            $my_result['root'] = $_host;
        }
        elseif(count($my_host) === 1)
        {
            // something like localhost
            $my_result['root'] = $_host;
        }
        elseif(count($my_host) === 2)
        {
            // like jibres.com
            $my_result['root'] = $my_host[0];
            $my_result['tld']  = $my_host[1];
        }
        elseif(count($my_host) >= 3)
        {
            // some conditons like
            // ermile.ac.ir
            // ermile.jibres.com
            // ermile.jibres.ac.ir
            // a.ermile.jibres.ac.ir

            // get last one as tld
            $my_result['tld']  = end($my_host);
            array_pop($my_host);

            // check last one after remove is probably tld or not
            $known_tld    = ['com', 'org', 'net', 'gov', 'co', 'ac', 'id', 'sch', 'biz'];
            $probably_tld = end($my_host);
            if(in_array($probably_tld, $known_tld))
            {
                $my_result['tld'] = $probably_tld. '.'. $my_result['tld'];
                array_pop($my_host);
            }

            $my_result['root'] = end($my_host);
            array_pop($my_host);

            // all remain is subdomain
            if(count($my_host) > 0)
            {
                $my_result['subdomain'] = implode('.', $my_host);
            }
        }

        return $my_result;
    }
$host = array_reverse(explode('.', $_SERVER['SERVER_NAME'])); if (count($host) >= 3){ echo "Main domain is = ".$host[1].".".$host[0]." & subdomain is = ".$host[2]; // Main domain is = example.com & subdomain is = sub } else { echo "Main domain is = ".$host[1].".".$host[0]." & subdomain not found"; // "Main domain is = example.com & subdomain not found"; }