Get hostname from url php

function url(){
    if(isset($_SERVER['HTTPS'])){
        $protocol = ($_SERVER['HTTPS'] && $_SERVER['HTTPS'] != "off") ? "https" : "http";
    }
    else{
        $protocol = 'http';
    }
    return $protocol . "://" . $_SERVER['HTTP_HOST'];
}

For example with the function above, it works fine if I work with the same directory, but if I make a sub directory, and work in it, it will give me the location of the sub directory also for example. I just want example.com but it gives me example.com/sub if I'm working in the folder sub. If I'm using the main directory,the function works fine. Is there an alternative to $_SERVER['HTTP_HOST']?

Show

    Or how could I fix my function/code to get the main url only? Thanks.

    asked Jun 19, 2013 at 20:56

    1

    Use SERVER_NAME.

    echo $_SERVER['SERVER_NAME']; //Outputs www.example.com
    

    answered Jun 19, 2013 at 21:01

    Get hostname from url php

    Bad WolfBad Wolf

    7,9664 gold badges33 silver badges43 bronze badges

    4

    You could use PHP's parse_url() function

    function url($url) {
      $result = parse_url($url);
      return $result['scheme']."://".$result['host'];
    }
    

    answered Jun 19, 2013 at 21:00

    3

    Shortest solution:

    $domain = parse_url('http://google.com', PHP_URL_HOST);
    

    answered May 11, 2017 at 9:08

    barbushinbarbushin

    5,1135 gold badges35 silver badges43 bronze badges

    6

    /**
     * Suppose, you are browsing in your localhost 
     * http://localhost/myproject/index.php?id=8
     */
    function getBaseUrl() 
    {
        // output: /myproject/index.php
        $currentPath = $_SERVER['PHP_SELF']; 
    
        // output: Array ( [dirname] => /myproject [basename] => index.php [extension] => php [filename] => index ) 
        $pathInfo = pathinfo($currentPath); 
    
        // output: localhost
        $hostName = $_SERVER['HTTP_HOST']; 
    
        // output: http://
        $protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https'?'https':'http';
    
        // return: http://localhost/myproject/
        return $protocol.'://'.$hostName.$pathInfo['dirname']."/";
    }
    

    answered May 6, 2016 at 11:17

    Get hostname from url php

    JasmeenJasmeen

    8569 silver badges16 bronze badges

    3

    Use parse_url() like this:

    function url(){
        if(isset($_SERVER['HTTPS'])){
            $protocol = ($_SERVER['HTTPS'] && $_SERVER['HTTPS'] != "off") ? "https" : "http";
        }
        else{
            $protocol = 'http';
        }
        return $protocol . "://" . parse_url($_SERVER['REQUEST_URI'], PHP_URL_HOST);
    }
    

    Here is another shorter option:

    function url(){
        $pu = parse_url($_SERVER['REQUEST_URI']);
        return $pu["scheme"] . "://" . $pu["host"];
    }
    

    answered Jun 19, 2013 at 21:01

    Get hostname from url php

    Get Off My LawnGet Off My Lawn

    31.9k34 gold badges157 silver badges301 bronze badges

    1

    Step-1

    First trim the trailing backslash (/) from the URL. For example, If the URL is http://www.google.com/ then the resultant URL will be http://www.google.com

    $url= trim($url, '/');
    

    Step-2

    If scheme not included in the URL, then prepend it. So for example if the URL is www.google.com then the resultant URL will be http://www.google.com

    if (!preg_match('#^http(s)?://#', $url)) {
        $url = 'http://' . $url;
    }
    

    Step-3

    Get the parts of the URL.

    $urlParts = parse_url($url);
    

    Step-4

    Now remove www. from the URL

    $domain = preg_replace('/^www\./', '', $urlParts['host']);
    

    Your final domain without http and www is now stored in $domain variable.

    Examples:

    http://www.google.com => google.com

    https://www.google.com => google.com

    www.google.com => google.com

    http://google.com => google.com

    answered Nov 28, 2017 at 9:22

    Get hostname from url php

    1

    2 lines to solve it

    $actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    $myDomain = preg_replace('/^www\./', '', parse_url($actual_link, PHP_URL_HOST));
    

    answered Apr 20, 2019 at 20:35

    Get hostname from url php

    FadiFadi

    2272 silver badges6 bronze badges

    1

    /* Get sub domain or main domain url
     * $url is $_SERVER['SERVER_NAME']
     * $index int remove subdomain if acceess from sub domain my current url is https://support.abcd.com ("support" = 7 (char))
     * $subDomain string 
     * $issecure string https or http
     * return url
     * call like echo getUrl($_SERVER['SERVER_NAME'],7,"payment",true,false);
     * out put https://payment.abcd.com
     * second call echo getUrl($_SERVER['SERVER_NAME'],7,null,true,true);
    */
    function getUrl($url,$index,$subDomain=null,$issecure=false,$www=true) {
      //$url=$_SERVER['SERVER_NAME']
      $protocol=($issecure==true) ?  "https://" : "http://";
      $url= substr($url,$index);
      $www =($www==true) ? "www": "";
      $url= empty($subDomain) ? $protocol.$url : 
      $protocol.$www.$subDomain.$url;
      return $url;
    }
    

    answered May 22, 2019 at 5:22

    Aasif khanAasif khan

    1311 silver badge8 bronze badges

    Use this code is whork :

    if (!preg_match('#^http(s)?://#', $url)) {
             $url = 'http://' . $url;
    }
    $urlParts = parse_url($url);
    $url = preg_replace('/^www\./', '', $urlParts['host']);
    

    answered Jan 11, 2021 at 0:02

    Get hostname from url php

    lookly Devlookly Dev

    3073 silver badges4 bronze badges

    1

    This works fine if you want the http protocol also since it could be http or https. $domainURL = $_SERVER['REQUEST_SCHEME']."://".$_SERVER['SERVER_NAME'];

    answered Apr 18, 2020 at 7:52

    Get hostname from url php

    RudolphRudolph

    1391 silver badge7 bronze badges

    Please try this:

    $uri = $_SERVER['REQUEST_URI']; // $uri == example.com/sub
    $exploded_uri = explode('/', $uri); //$exploded_uri == array('example.com','sub')
    $domain_name = $exploded_uri[1]; //$domain_name = 'example.com'
    

    I hope this will help you.

    Get hostname from url php

    Ismail RBOUH

    9,9942 gold badges23 silver badges36 bronze badges

    answered Jul 14, 2016 at 14:49

    CharlesCharles

    3102 silver badges8 bronze badges

    1

    Tenary Operator helps keep it short and simple.

    echo (isset($_SERVER['HTTPS']) ? 'http' : 'https' ). "://" . $_SERVER['SERVER_NAME']  ;
    

    answered Oct 2, 2018 at 17:09

    Get hostname from url php

    OluwaseyeOluwaseye

    6817 silver badges19 bronze badges

    1

    If you're using wordpress, use get_site_url:

    get_site_url()
    

    answered May 13, 2020 at 1:44

    ElronElron

    1,0701 gold badge11 silver badges20 bronze badges