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

谢谢你!


当前回答

短的方法

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

其他回答

一些变化:

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'] . '://';
 echo $scheme; //it gives http:// or https://

注意,这个服务器变量是不可靠的。欲了解更多信息,请查看: $_SERVER['REQUEST_SCHEME']是否可靠?

这也是一个迟到的派对,但这里是一个更短的版本的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://';

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

这对我很有用

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://';
}