title: get the main site folder path in php
body: <p>In PHP how can I get the site folder path anywhere in the site?<br /></p>
  
  <blockquote>
    <p>ex: /var/www/sitename</p>
  </blockquote>
  
  <p>this is what I got so far:</p>
  
  <pre><code>$r1 = $_SERVER['document_root']          //  = /var/www
  $r2 = __DIR__                           //  = /var/www/sitename/view/folder/subf
  $r3 = str_replace($r1 . '/', '', $r2);  //  = sitename/views/folder/subf
  $arr = explode('/', $r3);               //  = array (sitename, views, folder ...)
  $sitepath = $r1 . '/' . $arr[0]         //  = /var/www/sitename
  </code></pre>
  
  <p>Is there any other easiest way?.</p>
  
  <p>EDIT: there are many site copies in different servers with different names, could be site1 (/var/www/site1) or sitexx347(/var/www/sitexx347) or onemoresite.com (public_html/onemoresite), and I want to know it anywhere in the website so instead of calling</p>
  
  <pre><code>require_once '../../../../../../config.php';
  </code></pre>
  
  <p>or</p>
  
  <pre><code>require_once $_SERVER['DOCUMENT_ROOT'] . '/IveNoIdeaWhatTheNameIs/config.php';
  </code></pre>
  
  <p>I can do this:</p>
  
  <pre><code>require_once $sitepath . 'config.php';
  </code></pre>
  
  <p>I repeat, I have no idea what the site name is.</p>
  
  <p>EDIT 2: the way I do it now works perfect, I was just trying to know an easiest way. 
  Actually this can be shorten to do it like this:</p>
  
  <pre><code>$r = explode('/', str_replace($_SERVER['DOCUMENT_ROOT'].'/', '', __DIR__));
  $sitepath = $_SERVER['DOCUMENT_ROOT'] . '/' . $r[0];
  </code></pre>