There are four existing answers, but they all seem to deal with file paths, and you're asking about a base URL for web requests.
Given any web request, you get a bunch of keys in $_SERVER
that may be helpful. For example, in your mock example, you might have the following:
Thinking critically, how would you pull out the base URL for any given subrequest? In certain cases you can look at $_SERVER['REQUEST_URI']
and strip off trailing elements if you know how deep in your hierarchy the request is. (For example, if your script is two folders deep, strip off the last two path elements.) When PATH_INFO
or mod_rewrite
are in use, things become less clear: as longer and longer URLs are provided, there is no clear indication where the paths end and the dynamic URL begins.
This is why WordPress, MediaWiki, phpBB, phpMyAdmin, and every application I've ever written has the user manually specify a base URL as part of the application configuration.