1

With php, I want to return the current url of the page I am currently on.

for example, if this script is run on http://www.google.com, I want to echo out 'google' sans http://

OR

if this script is run on http://173.244.195.179, I want to echo out '173.244.195.179' sans http://

I've looked at $_SERVER but haven't been able to get it to work. Suggestions?

jimy
  • 4,848
  • 3
  • 35
  • 52
dukevin
  • 22,384
  • 36
  • 82
  • 111
  • 1
    You want to echo out 'google' or 'www.google.com' ? – Timon. Z May 04 '11 at 07:51
  • possible duplicate of [getting current URL](http://stackoverflow.com/questions/5216172/getting-current-url) – Pekka May 04 '11 at 07:54
  • @Pekka, I have read that post and none of those do this exactly – dukevin May 04 '11 at 07:59
  • ah, okay. This is not trivial, because there can be different scenarios: Consider `google.co.uk` where the last two parts must be stripped vs. `google.com` where it's only the last part. How do you plan to deal with this? – Pekka May 04 '11 at 08:03

1 Answers1

1
$domain = $_SERVER['HTTP_HOST'];
$ar = explode('.', $domain);

echo $ar[0];

Maybe?

EDIT: (Supports subdomains)

function domain()
{
    $ends = array('net','com','info','org');

    $domain = $_SERVER['HTTP_HOST'];
    $ar = explode('.', $domain);

    $result = '';

    $i = 0;
    $found = false;
    for($i; $i<sizeof($ar); $i++)
    {
        $j = 0;
        for($j; $j<sizeof($ends); $j++)
        {
            if($ends[$j] == $ar[$i]) $found = true;
        }

        if($found) break;
        $result .= $ar[$i] . '.';
    }

    return substr($result, 0, strlen($result)-1);
}

echo domain();

I'm going to put my money on that there's a way simpler or inbuilt way of doing this.

Marty
  • 39,033
  • 19
  • 93
  • 162
  • looks promising though one problem, the url of my site is `173.244.195.179` so the explode breaks this – dukevin May 04 '11 at 07:55
  • HTTP_HOST is the target host sent by the client. It can be manipulated freely by the user. It less reliable then SERVER_NAME since it's defined in the server configuration. [Check out this topic](http://stackoverflow.com/questions/2297403/http-host-vs-server-name) – Mark May 04 '11 at 08:06
  • If this is the case then simply replace HTTP_HOST with SERVER_NAME - my bad. – Marty May 04 '11 at 08:07