title: Get root URL for a PHP website
body: <p>I'm currently working on a PHP project and am looking for a way to get the URL for the root of the website; I have a configuration file at the root so I'm thinking as to using that to figure out the "base URL." I'm looking for a way to do it dynamically so I can locate the URL of the root of the website, i.e. <code>http://domain.com/my_app/</code>. I am doing my best to avoid using relative paths and am using PHP to generate the URLs for whatever I am using. For example, I am using PHP to generate CSS code and the CSS code link to images so I would like to get an absolute URL in here instead of a relative path.</p>
  
  <pre><code>my_app/
      admin/
          resources/
              css/
                  admin-css.php
              imgs/
                  login.png
      resources/
          css/
              css.php
          imgs/
              my-image.png
              shared-image.png
      config.php
  </code></pre>
  
  <p>In my <code>resources/css/css.php</code> file, I am looking at getting the "base URL" so I can generate an absolute URL to the <code>imgs</code> folder like <code>http://domain.com/resources/imgs/my-image.png</code> but currently I am getting <code>http://domain.com/resources/css/imgs/my-image.png</code> since the defines below look at getting the directory of the loaded PHP file, not the included one. I would also like to share images between the folders (i.e. access the <code>shared-image.png</code> file from the <code>admin</code> folder) so getting the base URL would be ideal in generating links. The reason I an avoiding relative paths is because I have a function that creates a URL, <code>createURL()</code>, so I can get all the URLs working without having to hard code anything.</p>
  
  <pre><code>&lt;?php
  DEFINE('HTTP_TYPE', $_SERVER['HTTP_X_FORWARDED_PROTO']);
  DEFINE('HTTP_ROOT', $_SERVER['HTTP_HOST']);
  DEFINE('HTTP_FOLDER', dirname($_SERVER['PHP_SELF']) . '/');
  DEFINE('BASE_URL', HTTP_TYPE . "://" . HTTP_ROOT . HTTP_FOLDER);
  
  function createURL($pathFromRoot)
  {
      return BASE_URL . $pathFromRoot;
  }
  </code></pre>
  
  <p>All of these defines are located in my configuration file, so I am thinking that the best way to do this is to get the URL for the config file (<code>http://domain.com/my_app/config.php</code>) and just strip the "config.php." Keep in mind, the website could be hosted deeper in a folder structure <code>http://domain.com/my_app/another/folder/config.php</code> or no sub folders <code>http://domain.com/config.php</code>.</p>
  
  <p>Is this possible, if so how can it be done? Or is there another approach I should follow?</p>