我写了一个小函数来建立当前的网站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吗?有必要检查一下协议吗?

谢谢你!


当前回答

这也是一个迟到的派对,但这里是一个更短的版本的Rid Iculous的答案使用空联合运算符:

$is_ssl = in_array($_SERVER['HTTPS'] ?? '', ['on', 1]) ||
          ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') == 'https';
$protocol = $is_ssl ? 'https://' : 'http://';

Or:

$protocol = in_array($_SERVER['HTTPS'] ?? '', ['on', 1]) ||
            ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') == 'https' ?
            'https://' : 'http://';

其他回答

这也是一个迟到的派对,但这里是一个更短的版本的Rid Iculous的答案使用空联合运算符:

$is_ssl = in_array($_SERVER['HTTPS'] ?? '', ['on', 1]) ||
          ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') == 'https';
$protocol = $is_ssl ? 'https://' : 'http://';

Or:

$protocol = in_array($_SERVER['HTTPS'] ?? '', ['on', 1]) ||
            ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') == 'https' ?
            'https://' : 'http://';

它不是自动的。上面的函数看起来不错。

一些变化:

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

我是这样做的……这是Rid Iculous的答案的简写版……

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


echo $protocal;