Just to clarify (people seem to be all over the place on explaining it) web root is simply the physical directory on the server OS that your HTTP server is treating as root (/) for the domain.
A while ago I needed the web root on a host that wouldn’t provide it… so I wrote some PHP to figure it out. Mostly it’s a matter of just stripping FILE from the end of $_SERVER[‘PHP_SELF’] thus:
function webRoot() {
return str_replace(
$_SERVER['PHP_SELF'],
'',
/* correct for windows slashes */
str_replace('\\\\','/',__FILE__)
);
}
Simple little test proggy:
echo '<pre>
PHP_SELF : ',$_SERVER['PHP_SELF'],'
__FILE__ : ',__FILE__,'
Web Root : ',webRoot(),'
</pre>';
To show it in action… run on XAMPP on my win7 machine I get this for output:
PHP_SELF : /webRoot.php
__FILE__ : C:\\web\\webRoot.php
Web Root : C:/web
Note the slash reversal… Windows using the opposite slash of the *nix world can be annoying at times.
Run from my old server (debian+ISPConfig):
PHP_SELF : /webRoot.php
__FILE__ : /var/www/web3/web/webRoot.php
Web Root : /var/www/web3/web
Run from my new hosting location (freeBSD, ngnix with passthrough to apache):
PHP_SELF : /webRoot.php
__FILE__ : /home/cutcodedown/public_html/webRoot.php
Web Root : /home/cutcodedown/public_html
With it changing from host to host and OS to OS and even *nix distro to *nix distro, it’s really best to pull the value automatically with a script like this… only problem is, a handful of faulty windblows php setups don’t report PHP_SELF properly… Pretty much I say “OH WELL” on that. Care also has to be taken as some mod_rewrite rules can screw it up as well.
Oh, in theory this should be the job of $_SERVER[‘DOCUMENT_ROOT’], but it returns the subdirectory currently being run from, not the actual http server root… and if the php configuration files are set wrong, it outputs total unreliable gibberish. I’ve never been able to use the value returned by DOCUMENT_ROOT in a meaningful manner.
Even when it works right, it doesn’t return web root, just doc root… you run it in \web\ est\webroot.php DOCUMENT_ROOT will sometimes return \web, sometimes return \web\ est, sometimes return \, sometimes return nothing at all, and I’ve seen it on occasion return total gibberish like a randomly generated hash.