PHP getting full server name including port number and protocol

前端 未结 9 1479
暗喜
暗喜 2020-12-16 12:00

In PHP, is there a reliable and good way of getting these things:

Protocol: i.e. http or https Servername: e.g. localhost Portnumber: e.g. 8080

9条回答
  •  悲&欢浪女
    2020-12-16 13:04

    Here's what I use:

        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;
        }
    

提交回复
热议问题