URL의 하위 도메인을 가져 오는 PHP 함수
PHP에 하위 도메인의 이름을 가져 오는 함수가 있습니까?
다음 예에서는 URL의 "en"부분을 가져오고 싶습니다.
en.example.com
다음은 한 줄 솔루션입니다.
array_shift((explode('.', $_SERVER['HTTP_HOST'])));
또는 귀하의 예를 사용하여 :
array_shift((explode('.', 'en.example.com')));
편집 : 이중 괄호를 추가하여 "변수 만 참조로 전달해야 함"을 수정했습니다.
편집 2 : PHP 5.4 에서 시작 하면 간단하게 할 수 있습니다.
explode('.', 'en.example.com')[0];
parse_url 함수를 사용합니다 .
$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);
먼저 도메인 이름 (예 : 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;
}
출력 :
0 => sub1.sub2
1 => sub1
2 =>
3 => sub1.sub2.sub3
4 => sub1.sub2.sub3
5 => sub1.sub2
<?php
$url = 'http://user:password@sub.hostname.tld/path?argument=value#anchor';
$array=parse_url($url);
$array['host']=explode('.', $array['host']);
echo $array['host'][0]; // returns 'en'
?>
도메인 접미사의 신뢰할 수있는 유일한 소스는 도메인 등록 기관이므로 해당 지식 없이는 하위 도메인을 찾을 수 없습니다. https://publicsuffix.org에 모든 도메인 접미사가있는 목록이 있습니다 . 이 사이트는 또한 PHP 라이브러리 ( https://github.com/jeremykendall/php-domain-parser)로 연결됩니다 .
아래에서 예를 찾으십시오. 또한 다중 접미사 (co.uk)가있는 도메인 인 en.test.co.uk에 대한 샘플을 추가했습니다.
<?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;
간단히...
preg_match('/(?:http[s]*\:\/\/)*(.*?)\.(?=[^\/]*\..{2,5})/i', $url, $match);
$ 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);
}
가장 간단하고 빠른 솔루션.
$sSubDomain = str_replace('.example.com','',$_SERVER['HTTP_HOST']);
$REFERRER = $_SERVER['HTTP_REFERER']; // Or other method to get a URL for decomposition
$domain = substr($REFERRER, strpos($REFERRER, '://')+3);
$domain = substr($domain, 0, strpos($domain, '/'));
// This line will return 'en' of 'en.example.com'
$subdomain = substr($domain, 0, strpos($domain, '.'));
내가 가장 좋고 짧은 해결책을 찾은 것은
array_shift(explode(".",$_SERVER['HTTP_HOST']));
'오류 : 엄격한 기준 : 변수 만 참조로 전달되어야합니다.' 다음과 같이 사용하십시오.
$env = (explode(".",$_SERVER['HTTP_HOST'])); $env = array_shift($env);
$domain = 'sub.dev.example.com';
$tmp = explode('.', $domain); // split into parts
$subdomain = current($tmp);
print($subdomain); // prints "sub"
이전 질문에서 볼 수 있듯이 PHP로 첫 번째 하위 도메인을 얻는 방법은 무엇입니까?
실제로 100 % 동적 인 솔루션은 없습니다. 그냥 알아 내려고 노력했지만 다른 도메인 확장 (DTL)으로 인해이 모든 확장을 실제로 구문 분석하고 매번 확인하지 않으면이 작업이 정말 어려울 것입니다.
.com vs .co.uk vs org.uk
가장 신뢰할 수있는 옵션은 실제 도메인 이름을 저장하는 상수 (또는 데이터베이스 항목 등)를 정의하고 $_SERVER['SERVER_NAME']
사용 에서 제거하는 것입니다.substr()
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, '.');
}
이제이 기능을 사용 http://test.mymaindomain.co.uk
하는 경우 제공 test
되거나 여러 하위 도메인 수준 http://another.test.mymaindomain.co.uk
이있는 another.test
경우 얻을 수 있습니다 DOMAIN
. 물론 .
이게 도움이 되길 바란다.
간단히
reset(explode(".", $_SERVER['HTTP_HOST']))
이것은 내 솔루션이며 가장 일반적인 도메인에서 작동하며 필요에 따라 확장 배열을 맞출 수 있습니다.
$ SubDomain = explode ( '.', explode ( '| ext |', str_replace (array ( '. com', '.net', '.org'), '| ext |', $ _ SERVER [ 'HTTP_HOST']) )) [0]);
정규식, 문자열 함수, parse_url () 또는 그 조합을 사용하는 것은 실제 솔루션이 아닙니다. domain을 사용하여 제안 된 솔루션을 테스트하면 test.en.example.co.uk
올바른 결과가 없습니다.
올바른 해결책은 Public Suffix List로 도메인을 구문 분석하는 패키지를 사용하는 것 입니다. TLDExtract를 추천 합니다 . 다음은 샘플 코드입니다.
$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'
PHP 7.0 : 분해 기능 사용 및 모든 결과 목록 생성.
list($subdomain,$host) = explode('.', $_SERVER["SERVER_NAME"]);
예 : sub.domain.com
echo $subdomain;
결과 : 하위
echo $host;
결과 : 도메인
// For www.abc.en.example.com
$host_Array = explode(".",$_SERVER['HTTP_HOST']); // Get HOST as array www, abc, en, example, com
array_pop($host_Array); array_pop($host_Array); // Remove com and exmaple
array_shift($host_Array); // Remove www (Optional)
echo implode($host_Array, "."); // Combine array abc.en
내가 게임에 정말 늦었다는 것을 알고 있지만 여기에 있습니다.
What I did was take the HTTP_HOST server variable ($_SERVER['HTTP_HOST']
) and the number of letters in the domain (so for example.com
it would be 11).
Then I used the substr
function to get the subdomain. I did
$numberOfLettersInSubdomain = strlen($_SERVER['HTTP_HOST'])-12
$subdomain = substr($_SERVER['HTTP_HOST'], $numberOfLettersInSubdomain);
I cut the substring off at 12 instead of 11 because substrings start on 1 for the second parameter. So now if you entered test.example.com, the value of $subdomain
would be test
.
This is better than using explode
because if the subdomain has a .
in it, this will not cut it off.
if you are using drupal 7
this will help you:
global $base_path;
global $base_root;
$fulldomain = parse_url($base_root);
$splitdomain = explode(".", $fulldomain['host']);
$subdomain = $splitdomain[0];
$host = $_SERVER['HTTP_HOST'];
preg_match("/[^\.\/]+\.[^\.\/]+$/", $host, $matches);
$domain = $matches[0];
$url = explode($domain, $host);
$subdomain = str_replace('.', '', $url[0]);
echo 'subdomain: '.$subdomain.'<br />';
echo 'domain: '.$domain.'<br />';
From PHP 5.3 you can use strstr() with true parameter
echo strstr($_SERVER["HTTP_HOST"], '.', true); //prints en
Try this...
$domain = 'en.example.com';
$tmp = explode('.', $domain);
$subdomain = current($tmp);
echo($subdomain); // echo "en"
function get_subdomain($url=""){
if($url==""){
$url = $_SERVER['HTTP_HOST'];
}
$parsedUrl = parse_url($url);
$host = explode('.', $parsedUrl['path']);
$subdomains = array_slice($host, 0, count($host) - 2 );
return implode(".", $subdomains);
}
you can use this too
echo substr($_SERVER['HTTP_HOST'], 0, strrpos($_SERVER['HTTP_HOST'], '.', -5));
I'm doing something like this
$url = https://en.example.com
$splitedBySlash = explode('/', $url);
$splitedByDot = explode('.', $splitedBySlash[2]);
$subdomain = $splitedByDot[0];
We use this function to handle multiple subdomain and multiple tld also handle ip and localhost
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;
}
Suppose current url = sub.example.com
$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"; }
If you only want what comes before the first period:
list($sub) = explode('.', 'en.example.com', 2);
참고URL : https://stackoverflow.com/questions/5292937/php-function-to-get-the-subdomain-of-a-url
'development' 카테고리의 다른 글
컴파일 문제 : crt1.o를 찾을 수 없음 (0) | 2020.08.13 |
---|---|
가장 정확한 결과를 얻으려면 어떤 순서로 수레를 추가해야합니까? (0) | 2020.08.13 |
PHP에서 두 날짜를 비교하는 방법 (0) | 2020.08.13 |
서로를 참조하는 두 목록을 똑같은 방식으로 정렬 할 수 있습니까? (0) | 2020.08.13 |
curl -v의 출력을 어떻게 파이프하거나 리디렉션합니까? (0) | 2020.08.13 |