title: How to programmatically determine the document root in PHP?
body: <p>Here's a problem that I've been running into lately - a misconfigured apache on a webhost. This means that all scripts that rely on <code>$_SERVER['DOCUMENT_ROOT']</code> break. The easiest workaround that I've found is just set the variable in some global include files that is shared, but it's a pain not to forget it. My question is, how do I determine the correct document root programatically?</p>
  
  <p>For example, on one host, the setup is like this:</p>
  
  <pre><code>$_SERVER['DOCUMENT_ROOT'] == '/htdocs'
  </code></pre>
  
  <p>The real document roots are:</p>
  
  <pre><code>test.example.com -&gt; /data/htdocs/example.com/test
  www.example.com -&gt; /data/htdocs/example.com/www
  </code></pre>
  
  <p>And I'd like a script that's run from <code>www.example.com/blog/</code> (on the path <code>/data/htdocs/example.com/www/blog</code>) to get the correct value of <code>/data/htdocs/example.com/www</code>.</p>
  
  <p>On another host, the setup is a bit different:</p>
  
  <pre><code>$_SERVER['DOCUMENT_ROOT'] == '/srv'
  test.example.com -&gt; /home/virtual_web/example.com/public_html/test
  www.example.com -&gt; /home/virtual_web/example.com/public_html/www
  </code></pre>
  
  <p>Is there any solution to this? Or is the only way simply not to ever rely on <code>$_SERVER['DOCUMENT_ROOT']</code> and fix all the software that I'm running on my sites? Fixing this on the hosting's side doesn't seem to be an option, I've yet to encounter a host where this is was configured correctly. The best I got was a document root pointing to www.example.com, which was at least inside open_basedir - they used yet another naming scheme, www.example.com would point to <code>/u2/www/example_com/data/www/</code>.</p>