IT

PHP 사이트 URL 프로토콜 가져 오기-http 및 https

lottoking 2020. 5. 14. 08:17
반응형

PHP 사이트 URL 프로토콜 가져 오기-http 및 https


현재 사이트 URL 프로토콜을 설정하는 작은 기능을 작성했지만 SSL이 없으며 https에서 작동하는지 테스트하는 방법을 모릅니다. 이것이 올바른지 말해 주실 수 있습니까?

function siteURL()
{
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $domainName = $_SERVER['HTTP_HOST'].'/';
    return $protocol.$domainName;
}
define( 'SITE_URL', siteURL() );

위와 같이해야합니까, 아니면 그냥 할 수 있습니까? :

function siteURL()
{
    $protocol = 'http://';
    $domainName = $_SERVER['HTTP_HOST'].'/'
    return $protocol.$domainName;
}
define( 'SITE_URL', siteURL() );

SSL에서 앵커 태그 URL이 http를 사용하더라도 서버가 자동으로 URL을 https로 변환하지 않습니까? 프로토콜을 확인해야합니까?

감사합니다!


자동이 아닙니다. 당신의 최고 기능은 좋아 보인다.


이런 종류의 문제를 해결하는 훨씬 편리한 방법이 있지만 늦었습니다. 위에 표시된 솔루션은 매우 지저분하며 누군가 다시 확인 해야하는 경우 어떻게해야합니까?

$protocol = stripos($_SERVER['SERVER_PROTOCOL'],'https') === 0 ? 'https://' : 'http://';

또는 마음에 들지 않으면 조건없이

$protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,strpos( $_SERVER["SERVER_PROTOCOL"],'/'))).'://';

보세요 $_SERVER["SERVER_PROTOCOL"]


이것은 나를 위해 작동

if (isset($_SERVER['HTTPS']) &&
    ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) ||
    isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
    $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
  $protocol = 'https://';
}
else {
  $protocol = 'http://';
}

일부 변경 사항 :

function siteURL() {
  $protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || 
    $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
  $domainName = $_SERVER['HTTP_HOST'];
  return $protocol.$domainName;
}

짧은 길

$scheme = $_SERVER['REQUEST_SCHEME'] . '://';

나에 따르면 포트 번호 테스트는 좋은 습관이 아니기 때문에 내 솔루션은 다음과 같습니다.

define('HTTPS', isset($_SERVER['HTTPS']) && filter_var($_SERVER['HTTPS'], FILTER_VALIDATE_BOOLEAN));

HTTPS불변는 TRUE경우 $_SERVER['HTTPS']설정 또는 "예" "에", "1"을 "true"로 동일합니다. 그렇지 않으면 FALSE를 반환합니다.


IIS를 제외한 모든 시스템의 경우 사이트 자체 URL을 정의하기에 충분합니다.

$siteURL='http'.(empty($_SERVER['HTTPS'])?'':'s').'://'.$_SERVER['HTTP_HOST'].'/';

또는

$siteURL='http'.(empty($_SERVER['HTTPS'])?'':'s').'://'.$_SERVER['SERVER_NAME'].'/';

정확히 원하는 것에 따라 달라집니다 : HTTP_HOST vs. SERVER_NAME


프록시의 경우 SERVER_PORT올바른 값을 제공하지 않을 수 있으므로 이것이 나를 위해 일한 것입니다.

$protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443 || $_SERVER['HTTP_X_FORWARDED_PORT'] == 443) ? "https://" : "http://"

이 서버 변수를 사용하여 프로토콜 세부 사항을 얻으십시오.

 $scheme = $_SERVER['REQUEST_SCHEME'] . '://';
 echo $scheme; //it gives http:// or https://

이 서버 변수는 신뢰할 수 없습니다. 자세한 내용 은 $ _SERVER [ 'REQUEST_SCHEME']를 신뢰할 수 있습니까?


내 시스템에서 작동 하는 Rid Iculous 의 답변을 사용하여 기능을 만들었습니다 .

function site_protocol() {
    if(isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&  $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')  return $protocol = 'https://'; else return $protocol = 'http://';
}

그것이 도움이되기를 바랍니다.


$protocal = 'http';
if ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || $_SERVER['HTTPS'] == 'on') {$protocal = 'https';}


echo $protocal;

I know this is an old question but I came across this today since I needed to test for this in my site. It seems the answers above are needlessly complicated. To establish the site protocol, all you have to do is test $_SERVER['HTTPS']

If the protocol is using HTTPS, then $_SERVER['HTTPS'] will return 'on'. If not, the variable will remain empty. For example:
// test if HTTPS is being used. If it is, the echo will return '$SSL_test: on'. If not HTTPS, '$SSL_test' will remain empty.

$SSL_test = $_SERVER['HTTPS'];

echo '<p>$SSL_test: '.$SSL_test.'</p>';

if($SSL_test == true) {
    echo 'You\'re using SSL';
} else {
    echo 'You\'re not using SSL';
} 

You can use the above to easily and cleanly test for HTTPS and implement accordingly. :)


I've tested the most voted answer and it didn't work for me, I ended up using:

$protocol = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';

Extracted from CodeIgniter :

if ( ! function_exists('is_https'))
{
    /**
     * Is HTTPS?
     *
     * Determines if the application is accessed via an encrypted
     * (HTTPS) connection.
     *
     * @return  bool
     */
    function is_https()
    {
        if ( ! empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off')
        {
            return TRUE;
        }
        elseif (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) === 'https')
        {
            return TRUE;
        }
        elseif ( ! empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off')
        {
            return TRUE;
        }

        return FALSE;
    }
}

it's the best solution of https or http use this :

<?php
$protocol = '//';  
$site_url = $protocol.$_SERVER["HTTP_HOST"];
?>

But can't display https or http, so it only use to link your site content like image, etc.

if want to redirect your site in https, add this code in .htaccess file :

<IfModule mod_rewrite.c>
 RewriteCond %{HTTP:CF-Visitor} '"scheme":"http"'
 RewriteRule ^(.*)$ https://www.your-domain.com$1 [L]
</IfModule>

Change www.your-domain.com with your dowmain name.


Here is how I do it ... it is a shorthand if else version of Rid Iculous's answer ...

$protocol = isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] === 'on' || $_SERVER['HTTPS'] === 1) || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ? 'https' : 'http';

참고URL : https://stackoverflow.com/questions/4503135/php-get-site-url-protocol-http-vs-https

반응형