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/
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? A URL consists of five parts: the scheme, subdomain, top-level domain, second-level domain, and subdirectory.
$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/'
Another simple way:
<?php $hostname = getenv('HTTP_HOST'); echo $hostname;
getenv
(PHP 4, PHP 5)
getenv — Gets the value of an environment variable
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With