PHP getting full server name including port number and protocol

前端 未结 9 1385
暗喜
暗喜 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:39
    $protocol = isset($_SERVER['HTTPS']) && (strcasecmp('off', $_SERVER['HTTPS']) !== 0);
    $hostname = $_SERVER['SERVER_ADDR'];
    $port = $_SERVER['SERVER_PORT'];
    
    0 讨论(0)
  • 2020-12-16 12:39

    Why don't you get full url like this

    strtolower(array_shift(explode("/",$_SERVER['SERVER_PROTOCOL'])))."://".$_SERVER['SERVER_NAME'];
    

    or (If you want host name from HTTP)

    strtolower(array_shift(explode("/",$_SERVER['SERVER_PROTOCOL'])))."://".$_SERVER['HTTP_HOST'];
    
    0 讨论(0)
  • 2020-12-16 12:41

    Compiled from above:

    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;
    }
    
    0 讨论(0)
  • 2020-12-16 12:41

    nothing worked serverside , something was wrong on APACHE and I had no access to the server and I ended up redirecting to http throught Javascript, It's not the ideal solution maybe this can save someone else in my situation

    <script>
    if(!window.location.href.startsWith('https')) 
        window.location.href = window.location.href.replace('http','https');
    </script>
    
    0 讨论(0)
  • 2020-12-16 12:51

    $_SERVER['SERVER_PORT'] will give you the port currently used.

    0 讨论(0)
  • 2020-12-16 12:52
    <?php
    
    $services = array('http', 'ftp', 'ssh', 'telnet', 'imap', 'smtp', 'nicname', 'gopher', 'finger', 'pop3', 'www');
    
    foreach ($services as $service) {
        $port = getservbyname($service, 'tcp');
        echo $service . ":- " . $port . "<br />\n";
    }
    
    ?>
    

    This is display all port numbers.

    If you already know port number you can do like this,

    echo  getservbyport(3306, "http");   // 80
    
    0 讨论(0)
提交回复
热议问题