on PHP includes();

i love PHP includes. they’re a big reason why i even use PHP. i was just collaborating on a project that used Dreamweaver templates, which I had never used before. they’re pretty handy, in their way: i was able to modify a template file and have the changes automatically registered in all the files based off the template (e.g.: i added some javascript to the template, and all the pages were updated with the same javascript while maintaining their individual content). where that gets really unfun, though (and where includes rock the snot off xhtml) is that i had to re-upload every single page in the site when i made changes like that. w/include, i just re-upload the included file.

anyway, i got to thinking about hierarchy with includes b/c a lot of the includes i used for the site were included in different folders and different levels of the site hierarchy. i have a tendancy to put navigation bars in includes for obvious reasons. this can get a little dicey when you move up and down the hierarchy though.

say i’ve got an include that has my navigation bar, with the first item being a link to the homepage:

<li><a href=”index.php”>Home</a></li>

include this in any file that’s in the root directory and i’m fine. but if i move it into another folder (like zbrustudios.com/pictures/) and it would need to be:

<li><a href=”../index.php”>Home</a></li>

when i’m dealing with large sites, i figured out that this gets all sorts of troublesome when lots of including is done. my simple work around?

in every page i declare a php variable for the depth. so at the root level:

$depth = “”;

in a folder (like zbrustudios.com/pictures/):

$depth = “../”;

and even deeper (zbrustudios.com/pictures/vacation/):

$depth = “../../”;

then in the navigation file that i include on each of these pages the link looks like this:

<li><a href=”<?=$depth;?>index.php”>Home</a></li>

voilà!

December 7, 2008 • Posted in: php

Leave a Reply