PHP getting full server name including port number and protocol

前端 未结 9 1386
暗喜
暗喜 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 12:55

    Have a look at the documentation.

    You want $_SERVER['SERVER_PORT'] I think.

    0 讨论(0)
  • 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;
        }
    
    0 讨论(0)
  • 2020-12-16 13:04
     if(strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,4))=='http') {
            $strOut = sprintf('http://%s:%d', 
                           $_SERVER['SERVER_ADDR'],
                           $_SERVER['SERVER_PORT']);
        } else {
             $strOut = sprintf('https://%s:%d', 
                           $_SERVER['SERVER_ADDR'],
                           $_SERVER['SERVER_PORT']);
        }
    
     return $strOut;
    

    Try something like that if you want

    0 讨论(0)
提交回复
热议问题