Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the root url of the site?

Tags:

php

Might be a trivial question, but I am looking for a way to say get the root of a site url, for example: http://localhost/some/folder/containing/something/here/or/there should return http://localhost/

I know there is $_SERVER['DOCUMENT_ROOT'] but that's not what I want.

I am sure this is easy, but I have been reading: This post trying to figure out what i should use or call.

Ideas?

The other question I have, which is in relation to this one is - will what ever the answer be, work on sites like http://subsite.localhost/some/folder/containing/something/here/or/there so my end result is http://subsite.localhost/

like image 989
Adam Avatar asked Aug 13 '13 23:08

Adam


People also ask

What does root URL mean?

A root URL is the start or index page of a domain on a web server. Colloquially, many users call the homepage the “root URL” as well.

What are the parts of a URL?

What are the parts of a URL? A URL consists of five parts: the scheme, subdomain, top-level domain, second-level domain, and subdirectory.


2 Answers

$root = (!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/'; 

If you're interested in the current script's scheme and host.

Otherwise, parse_url(), as already suggested. e.g.

$parsedUrl = parse_url('http://localhost/some/folder/containing/something/here/or/there'); $root = $parsedUrl['scheme'] . '://' . $parsedUrl['host'] . '/'; 

If you're also interested in other URL components prior to the path (e.g. credentials), you could also use strstr() on the full URL, with the "path" as the needle, e.g.

$url = 'http://user:pass@localhost:80/some/folder/containing/something/here/or/there'; $parsedUrl = parse_url($url); $root = strstr($url, $parsedUrl['path'], true) . '/';//gives 'http://user:pass@localhost:80/' 
like image 90
boen_robot Avatar answered Sep 28 '22 18:09

boen_robot


Another simple way:

<?php $hostname = getenv('HTTP_HOST'); echo $hostname; 

getenv

(PHP 4, PHP 5)

getenv — Gets the value of an environment variable

like image 39
daniel__ Avatar answered Sep 28 '22 17:09

daniel__