Skip to content


Simple/Beginner’s PHP Website Template

This silly little ‘guide’ is meant for beginners in PHP. It’s a super quick template you can begin a website with (I claim no copyright to the code I wrote below, do what you want with it). Managing a site is much easier if the common elements are made dynamically, and for this it is best if you begin with clear, simple standards you can pick up on again later when you return to editing the site.

My code here is meant to be ‘quick and dirty’, getting the job done in the most obvious of ways. It can of course be used around CSS styles, and note also that a proper site would have the standard HTML/head/body tags. In the template code below, common template elements (header and footer) are included in each web page. This way, only one template file must be edited if site-spanning template pieces must be altered. That is, one page holds links which appear in a menu on all pages in the website, for instance. It is a bit redundant, but the .tpl.php files are stored in the sub-directory ‘tpl’ within the root directory where index.php stays.

Note that PHP5 allows included files to inherit variable scope from the parent page – this way, the variables $curPage and $rootDir are passed along to the tpl files. From this, simple switches can be made depending on what the current page is, for instance keeping hyperlinks from appearing when you’re currently on the linked page.

Note also that there are (at least) two ways of going about making a PHP website template. One way is how I show here, where individual pages include template pieces while themselves showing the content. Another way would be to have a main page which assembles the entire page, putting the template together and then putting in content, so to the user it may actually look like the same page.

So..Hopefully this quick little demo will prove useful! Enjoy.

index.php: <?php $curPage = 'Home'; $rootDir = '.'; include("$rootDir/tpl/links.tpl.php"); echo 'content here'; include("$rootDir/tpl/footer.tpl.php"); ?>
about.php: <?php $curPage = 'About'; $rootDir = '.'; include("$rootDir/tpl/links.tpl.php"); echo 'about this site here'; include("$rootDir/tpl/footer.tpl.php"); ?>
links.php: <?php $curPage = 'Links'; $rootDir = '.'; include("$rootDir/tpl/links.tpl.php"); echo 'Links Page'; include("$rootDir/tpl/footer.tpl.php"); ?>
links.tpl.php: <?php $homeLink = "<a href='$rootDir/'>Home</a>"; $aboutLink = "<a href='$rootDir/about.php'>About</a>"; $linksLink = "<a href='$rootDir/links.php'>Links</a>"; //Main site links
if($curPage == 'Home') $homeLink = "Home Pad"; echo "$homeLink | $aboutLink" ." | $linksLink"; echo '<hr />'; ?>
footer.tpl.php: <?php echo '<p>Footer information</p>'; ?>

Posted in How-To. Tagged with , , , , .

0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

You must be logged in to post a comment.