How do I get the root url of the site?
php
Solution
$root = (!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/';
If you're interested in the current script's scheme and host. Depending on web server configuration (reverse proxy, rewrites), what is "current" may not be what you see in the browser, but it is what PHP thinks it is dealing with.
Otherwise, if you have a URL at hand you want the root of, 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 substr() on the full URL, with the start of the "path" as the stop position, e.g.
$url = 'http://user:pass@localhost:80/some/folder/containing/something/here/or/there';
$parsedUrl = parse_url($url);
$root = substr($url, 0, strpos($url, $parsedUrl['path'], strlen($parsedUrl['scheme'] . '://'))) . '/';//gives 'http://user:pass@localhost:80/'
Note: The offset in strpos() is used to handle the case where the URL might already be the root.
Problem
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/`