PHP: Automatically Including Files from the Parent Tree

Wednesday, March 18, 2009

A common templating technique is to have identically named files with variables and functions in them that vary for each subdirectory that they are in. This way you can customize various data for each subdirectory. However, it can become an administrative problem to constantly make sure that each of your PHP files include all appropriate header/library files at all times.

Fortunately, it is possible to script this, making it an automatic process for you. The snippet below automatically includes any file named header.php from the current directory, or any directory higher than it but still within the web server's document root. As coded, this includes all header.php files, allowing for an inheritance scheme of sorts, because each subdirectory will have not only its header.php file included but also those from all its parent directories.

It is a small modification to this script to make it instead stop at the first one it finds, or perhaps to work backward, starting at the document root and including them from top to bottom.

Here's the code:

<?php
$curdir = str_replace('\\', '/', __FILE__);
// Store a copy of document root, ensuring forward slashes:
$root = str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']);

while ($root !== $curdir) {
    // Remove one directory level from the current directory
    $curdir = dirname($curdir);

    // Try to include the file, hide any error:
    @include("{$curdir}/header.php");
}
?>


The manipulation of the various directories to ensure forward slashes is just so that we know that our comparison between the root and current directory returns true. This is because on some operating systems, such as Windows, it is common for the __FILE__ constant and $_SERVER['DOCUMENT_ROOT'] to have different types of slashes in them. If you know the server that you are working on has consistent slashes, you can remove that portion of code.

Hope it helps.

0 comments: