The Apprentice Geek

I would fain grow old learning many things. ~ Plato

Coming from classic ASP to PHP development has it's share of learning curves. One of the first that I encountered was the use of server-side includes. In some ways I prefer the classic ASP model. For instance in classic ASP a server-side include to a path, relative to site root, is done like so:

            <!--#include virtual="/inc_folder/global_style_sheets.inc"-->
            <!--#include virtual="/inc_folder/global_javascript_includes.inc"-->
          

But PHP doens't like the concept of "root-relative" paths to includes and you'll get all kinds of errors if you try the following code on a page nested any lower than root level (i.e. "/blog/index.php"):

            <?include("/inc_folder/global_styles.inc");?>
            <?include("/inc_folder/global_javascript_includes.inc");?>
          

So we have to fake it by literally building the path relative to the current file. Like so:

            <?
            //Build the relative paths to all server-side include files
            $wwwRoot = substr_count($_SERVER["DOCUMENT_ROOT"],"\\");
            $thisPage = substr_count($_SERVER["PATH_TRANSLATED"],'\\');
            $steps = $thisPage - $wwwRoot;
            $sep = "";
            for($i=1;$i<$steps;$i++){
              $sep = $sep."../";
            }
            $styleSheets = $sep."inc_folder/global_styles.inc";
            $jScripts = $sep."inc_folder/global_javascripts.inc";
            ?>
          
Once all that is done we can finally put the relative paths to use as server-side include commands. Like so:
            <? include($styleSheets); ?>
            <? include($jScripts); ?>