Building a dynamic path to the document root for the include function


/ Published in: PHP
Save to your folder(s)

I like to build modular sites, always have, always will. We used to use frames to set up navigation links and headers and footers but there were so many issues with doing that. Then along came Server Side Includes (SSI) which allowed people to include those files at runtime into the page. Life was good.

PHP has this functionality, but one of the seriously frustrating things about it is the lack of being able to include files relative to the website root directory. This means you have to use the ../ syntax to back up a folder, sometimes multiple times, and then drill down through another folder.


Copy this code and paste it in your HTML
  1. <?php
  2. function dynRoot()
  3. {
  4. $levels = substr_count($_SERVER['PHP_SELF'],"/");
  5.  
  6. for ($i=0; $i < $levels - 1; $i++)
  7. {
  8. $relativeDir .= "../";
  9. }
  10.  
  11. return $relativeDir;
  12. }
  13. ?>

URL: http://www.devtek.org/tutorials/dynamic_document_root.php

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.