PHP, Website Design

PHP – Include the Same File from Different Folders

2 Comments

This is a PHP tutorial to add advanced include templates to your site.

What you need to know

  • Basic PHP functions: include(); and the “for” loop.

Background PHP Information

It is a very useful thing to use a template on your site. Once I have finished designing a site, and converted it into XHTML/CSS, I then make two (or more) includes out of it: “header.php” and “footer.php”. Those two includes have everything that is the same on every page of the site. This allows me to easily add or remove a button, change the layout, etc. All I have to do is change one file, and the entire site is updated!

What’s the Problem?

If you know includes, you know that they must be relative paths, not absolute. (So if your page is in the pages folder (/pages/) and your header.php is in the header folder (/header/), you will need to write your include like this:

include(../header/header.php);

The problem arises when you don’t want to hard code every new page, in every new folder.

PHP Solution

Here is a simple for loop that will figure out what folder you are in, and put the appropriate number of “../”s to make your includes work:

<?
$folder = split(“/”, $_SERVER[‘PHP_SELF’]);
$rootpath = “”;
for($count = count($folder); $count > 2; $count–){
$rootpath .= “../”;
}
include($rootpath . “include/header.php”);
?>

There you have it, some sweet, yet simple PHP.

-Enjoy,
-Ashton Sanders

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *