Programing

현재 도메인 받기

lottogame 2020. 7. 11. 09:58
반응형

현재 도메인 받기


서버에 내 사이트가 있습니다

http://www.myserver.uk.com

이를 위해 두 가지 도메인이 있습니다.

http://one.com

http://two.com

PHP 현재 도메인을 사용하고 싶지만 사용 $_SERVER['HTTP_HOST']하면이 표시가 나타납니다.

myserver.uk.com

대신에:

one.com or two.com

서버 이름이 아닌 도메인을 어떻게 얻을 수 있습니까? PHP 버전 5.2가 있습니다


이것을 사용해보십시오 : $_SERVER['SERVER_NAME']

또는 파싱

$_SERVER['REQUEST_URI']

편집하다:

apache_request_headers ()


가장 좋은 용도는

echo $_SERVER['HTTP_HOST'];

그리고 이렇게 사용할 수 있습니다

if(strpos( $_SERVER['HTTP_HOST'], 'banana.com') !== false){
    echo "Yes this is indeed the banana.com domain";
}

아래의이 코드는 키워드가 강조 표시된 구조화 된 HTML 출력에서 ​​$ _SERVER의 모든 변수를 볼 수있는 좋은 방법입니다. 실행 후 바로 중단됩니다. 때로는 어떤 것을 사용 해야할지 잊어 버렸기 때문에 이것이 좋을 것이라고 생각합니다.

<?php 
// change banana.com to the domain you were looking for.. 
$wordToHighlight= "banana.com";
$serverVarHighlighted = str_replace( $wordToHighlight, '<span style=\'background-color:#883399; color: #FFFFFF;\'>'. $wordToHighlight .'</span>',  $_SERVER );
echo "<pre>";
print_r( $serverVarHighlighted );
echo "</pre>";
exit();
?>

를 사용 $_SERVER['HTTP_HOST']하면 (subdomain.) maindomain.extension이 표시됩니다. 가장 쉬운 해결책 인 것 같습니다.

편집 : 실제로 iFrame을 통해 '리디렉션'하는 경우 도메인을 나타내는 get 매개 변수를 추가 할 수 있습니다.

<iframe src="myserver.uk.com?domain=one.com"/>

그런 다음 애플리케이션 전체에서이 데이터를 유지하는 세션 변수를 설정할 수 있습니다.


보안 문제에 대한 단일 언급없이이 답변이 어떻게 수십만 건의 의견을 받았는지 모르겠습니다.

다음을 사용할 수 있지만 안전하지 않습니다.

$_SERVER['HTTP_HOST']

이것은 요청 헤더에서 도메인을 가져옵니다.이 헤더는 해커가 조작 할 수 있으며 캐시 중독을 일으킬 수 있습니다.

$_SERVER['SERVER_NAME']

기본 Apache 설정에는 usecanonicalname 이 해제 $_SERVER['SERVER_NAME']되어있어 동일한 헤더로 채워진 $_SERVER['HTTP_HOST']어쨌든 포트와 함께 사용됩니다. 다음은 몇 가지 악의적 인 예 입니다. usecanonicalname이 켜져 있으면 더 안전하지만 해당 유형의 구성이 대부분의 환경에서 작동하는지는 알 수 없습니다.

주의 사항 :

  • serverName을 확인할 수 없으면 운영 체제의 호스트 이름 명령이 [source] 대신 사용됩니다 .
  • 레드햇 회전은 기본 [가에 usecanonical 소스 ].
  • 호스트 헤더가 없으면 서버는 usecanonical이 [source] 에있는 것처럼 작동합니다 .

올바른 방법

보안이 보장되는 유일한 방법은 액세스 할 수있는 도메인 이름을 저장하는 것입니다.

많은 프레임 워크가 이미이 작업을 처리하므로 특정 프레임 워크에 대한 설명서를 참조하십시오. 프레임 워크를 사용하지 않는 경우 다음 방법 중 하나가 작동합니다.

+ ---------------------------------------------- +- ---------------------- +
| 현재 도메인을 저장하는 안전한 방법 | 기본 / 권장 |
+----------------------------------------------+------------------------+
| Config file                                  | Joomla, Drupal/Symfony |
| Database                                     | WordPress              |
| Environmental variable                       | Laravel                |
| Service registry                             | Kubernetes DNS         |
+----------------------------------------------+------------------------+

For WordPress users

If you're using WordPress, you can securely get the domain like so:

$urlparts = parse_url(home_url());
$domain = $urlparts['host'];

(But if you're constructing a URL in WordPress, just use home_url or site_url, or any of the other URL functions.)



Try $_SERVER['SERVER_NAME']. Tips: Create a PHP file that calls the function phpinfo() and see the "PHP Variables" section. There is a bunch of useful variables we never thought there.


Late answer, but here it goes:

$currentDomain = preg_replace('/www\./i', '', $_SERVER['SERVER_NAME']);

It will give you a clean domain name, without www


I know this might not be entirely on the subject, but in my experience, I find storing WWW-ness of current URL in a variable useful.

Edit: In addition, please see my comment below, to see what this is getting at.

This is important when determining whether to dispatch Ajax calls with "www", or without:

$.ajax("url" : "www.site.com/script.php", ...

$.ajax("url" : "site.com/script.php", ...

When dispatching an Ajax call the domain name must match that of in the browser's address bar, otherwise you will have Uncaught SecurityError in console.

So I came up with this solution to address the issue:

<?php
    substr($_SERVER['SERVER_NAME'], 0, 3) == "www" ? $WWW = true : $WWW = false;

    if ($WWW) {
        /* We have www.example.com */
    } else {
        /* We have example.com */
    }
?>

Then, based on whether $WWW is true, or false run the proper Ajax call.

I know this might sound trivial, but this is such a common problem that is easy to trip over.


sorry For the Late answer everybody is using parse_url function but some times user may pass the argumet in different format

so as to fix that i have created the finction check this out

function fixDomainName($url='')
    {
        $strToLower = strtolower(trim($url));
        $httpPregReplace = preg_replace('/^http:\/\//i', '', $strToLower);
        $httpsPregReplace = preg_replace('/^https:\/\//i', '', $httpPregReplace);
        $wwwPregReplace = preg_replace('/^www\./i', '', $httpsPregReplace);
        $explodeToArray = explode('/', $wwwPregReplace);
        $finalDomainName = trim($explodeToArray[0]);
        return $finalDomainName;
    }

just pass the url and get the domain For example

echo fixDomainName('https://stackoverflow.com');

will return the result will be

stackoverflow.com

and in some situation

echo fixDomainName('stackoverflow.com/questions/id/slug');

and it will also return stackoverflow.com

Hope it Helps


$_SERVER['HTTP_HOST'] 

//to get the domain

$protocol=strpos(strtolower($_SERVER['SERVER_PROTOCOL']),'https') === FALSE ? 'http' : 'https';
$domainLink=$protocol.'://'.$_SERVER['HTTP_HOST'];

//domain with protocol

$url=$protocol.'://'.$_SERVER['HTTP_HOST'].'?'.$_SERVER['QUERY_STRING'];

//protocol,domain,queryString total **As the $_SERVER['SERVER_NAME'] is not reliable for multi domain hosting!


Simply try:

echo apache_request_headers()[3];

참고URL : https://stackoverflow.com/questions/10717249/get-current-domain

반응형