Website Designers and Webmasters

Dedicated to all the tasks Webmasters, Website Developers and Website Designers find themselves facing.

PHP – Include the Same File from Different Folders

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

Tags: , , ,

2 Comments »

  1. Thanks

    Comment by raman — May 28, 2009 @ 3:57 pm

  2. Thanks, I’ve just been trying to figure this out!

    Comment by Colin — October 26, 2009 @ 6:02 pm

RSS feed for comments on this post. TrackBack URL

Leave a comment