74
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']?

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

Zera42
  • 2,592
  • 1
  • 21
  • 33

13 Answers13

117

Use SERVER_NAME.

echo $_SERVER['SERVER_NAME']; //Outputs www.example.com
Bad Wolf
  • 8,206
  • 4
  • 34
  • 44
56

You could use PHP's parse_url() function

function url($url) {
  $result = parse_url($url);
  return $result['scheme']."://".$result['host'];
}
  • `$_SERVER['SERVER_NAME']` wasn't an option since we do interactive domain hosting with custom ports. (Why should we make things easy ?) – programaths Nov 07 '14 at 10:48
  • 1
    I believe parse_url return nothing, if no http. For example: $url = "example.com"; – Deepak Rajpal Feb 08 '19 at 11:15
  • 2
    Please add some explanation to your answer by editing it, such that others can learn from it - where does `$url` come from? – Nico Haase Apr 08 '20 at 13:20
38

Shortest solution:

$domain = parse_url('http://google.com', PHP_URL_HOST);
barbushin
  • 5,165
  • 5
  • 37
  • 43
  • 4
    This should be accepted as answer, because its cross domain capability – Naveen DA Dec 27 '17 at 05:23
  • 14
    This gives you the string "google.com". It's a flat out wrong answer. – Andrew Magill May 03 '18 at 00:59
  • 1
    @AyexeM You're supposed to change "google.com" to your website's domain. – undo Dec 02 '18 at 18:10
  • 18
    @rahuldotech That makes no sense, copy paste your domain in there and it will return your domain? How is that helpful ? OP wants the domain of the server, not how to parse a domain from a string. – Andrew Magill Feb 26 '19 at 18:34
  • 1
    How I understand the question is how to get the domain segment without knowing what the domain is. That is, relative to the page you are loading. What if you are testing locally, then uploading to production? If you already know the domain, you don't need to retrieve it dynamically. I think the assumption is we don't know the domain the resource is loading from. – TARKUS Jun 04 '19 at 11:13
  • You may want to use this snippet on several websites you have and dynamically always be able to insert the domain name into somewhere in your code. – Michael Moriarty Jan 30 '20 at 05:51
30
/**
 * 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']."/";
}
Jasmeen
  • 876
  • 9
  • 16
  • 1
    Umm... see php.net/manual/en/reserved.variables.server.php `$_SERVER["SERVER_PROTOCOL"]` returns a string like `HTTP/1.0` or `HTTP/1.1` and has nothing to do with https. You're probably looking for something like `$_SERVER['HTTPS'] == 'on'` or the undocumented `REQUEST_SCHEME`. See [this related question](https://serverfault.com/questions/827850/what-exactly-does-the-variable-server-protocol-actually-contain-apache-2-4) and here's the answer I used: http://stackoverflow.com/a/14270161/466314 – Ultimater May 10 '17 at 07:30
  • See, Previously I have wrote 5, It was correct but minor changes should be there like, $protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https'?'https':'http'; – Jasmeen May 11 '17 at 06:31
  • 1
    No, `strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https'‌​` is always false because $_SERVER["SERVER_PROTOCOL"] doesn't work the way you think it does. It will never contain HTTPS anywhere in it. The example given in the apache documentation `` is wrong as it's always true: https://httpd.apache.org/docs/2.4/rewrite/remapping.html#canonicalhost – Ultimater May 12 '17 at 23:29
11

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"];
}
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
6

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

Dibyendu Mitra Roy
  • 1,604
  • 22
  • 20
2

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));
Fadi
  • 267
  • 2
  • 6
2
/* 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;
}
Aasif khan
  • 161
  • 2
  • 8
2

Use this code is whork :

if (!preg_match('#^http(s)?://#', $url)) {
         $url = 'http://' . $url;
}
$urlParts = parse_url($url);
$url = preg_replace('/^www\./', '', $urlParts['host']);
lookly Dev
  • 325
  • 3
  • 5
  • This answer is missing its educational explanation. Also, I would prepare the url with a single preg call instead of two. ...and please use correct spelling. – mickmackusa Jan 11 '21 at 00:19
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'];

Rudolph
  • 139
  • 1
  • 8
0

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.

Ismail RBOUH
  • 10,292
  • 2
  • 24
  • 36
Charles
  • 320
  • 2
  • 8
  • In here $domain_name = 'sub' not 'example.com'. If need to get 'example.com' , then change the last code to $domain_name = $exploded_uri[0]; – Udara Herath Jan 04 '17 at 11:58
-2

Tenary Operator helps keep it short and simple.

echo (isset($_SERVER['HTTPS']) ? 'http' : 'https' ). "://" . $_SERVER['SERVER_NAME']  ;
Oluwaseye
  • 685
  • 8
  • 20
-3

If you're using wordpress, use get_site_url:

get_site_url()
Elron
  • 1,235
  • 1
  • 13
  • 26