PHP获取完整的服务器名称,包括端口号和协议

ale*_*ale 17 php

在PHP中,是否有一种可靠而好的方法来获取这些东西:

协议:即http或https Servername:例如localhost Portnumber:例如8080

我可以使用获取服务器名称$_SERVER['SERVER_NAME'].

我可以得到协议,但我不认为它是完美的:

    if(strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https') {
        return "https";
    }
    else {
        return "http";
    }
Run Code Online (Sandbox Code Playgroud)

我不知道如何获得端口号.我使用的端口号不是80 ..它们是8080和8888.

谢谢.

Jon*_*nix 31

看看文档.

你想要$_SERVER['SERVER_PORT']我想.

  • if($_SERVER['SERVER_PORT'] != '443') { $URL = 'https://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']; header("位置:$URL"); ?><script>window.location = "<?=$URL?>"</script><? } (2认同)

sbr*_*bot 13

返回完整协议服务器端口信息的函数:

function getMyUrl()
{
  $protocol = (!empty($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) == 'on' || $_SERVER['HTTPS'] == '1')) ? 'https://' : 'http://';
  $server = $_SERVER['SERVER_NAME'];
  $port = $_SERVER['SERVER_PORT'] ? ':'.$_SERVER['SERVER_PORT'] : '';
  return $protocol.$server.$port;
}
Run Code Online (Sandbox Code Playgroud)


lfj*_*eff 6

这是我使用的:

    function my_server_url()
    {
        $server_name = $_SERVER['SERVER_NAME'];

        if (!in_array($_SERVER['SERVER_PORT'], [80, 443])) {
            $port = ":$_SERVER[SERVER_PORT]";
        } else {
            $port = '';
        }

        if (!empty($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) == 'on' || $_SERVER['HTTPS'] == '1')) {
            $scheme = 'https';
        } else {
            $scheme = 'http';
        }
        return $scheme.'://'.$server_name.$port;
    }
Run Code Online (Sandbox Code Playgroud)


Nar*_*arf 5

$_SERVER['SERVER_PORT'] 将为您提供当前使用的端口.