PHP has many different template solutions, and the beauty of them all is how simple it makes maintaining and changing your website. Back in the day when everything was handled with static HTML files – if you needed to add a new link to your main menu – you found yourself editing dozens if not hundreds of different files.  With PHP you can break up your website into several sections, includes if you will. So the menu code can all be within 1 single file, which you include on other pages. This way all you have to do to change the menu on every single page is to edit one file.

Now in this tutorial we’ll build a very simple PHP template system which will utilize 2 files: a header.html and a footer.html – with which you can update the entire look of your website. The system can also can be used with query strings which means you can essentially have 4 files (header.html,footer.html,news.html, and core.php) to run your entire website.

Now the code below is very simple and i will try to explain the functions of each tag as much as possible.


Let’s start off with the first line –

require('header.php');

. This line will take the contents of our header.php file and include it into our page. So – here is where we can put the top section of our website – basically everything surrounding our content on top.

Moving past that we see the following:

$page = $_GET['page'];
if (($page == "home") or ($page =="")) { include('content/home.php');
} else if($page == "about") {
include('content/about.php');
}

Now what this code does is check to see what page the user is requesting. If the user is requesting the “home” page, or has not specified a page at all – the script will automatically load the home.php file. If the “about” page is specified- the about.php file will be loaded. Accessing these pages is done directly via the URL, so you would link to your about page like so: http://mywebsite.com/index.php?page=about.

Adding more pages is fairly simple – just copy/paste the following code, and put it directly underneath the prior else/if command:

else if($page == "contact"){
include('content/contact.php');
}

So you should have the following now:


Now you have 3 different content pages – home, about, and contact. All you need to do is create the content pages, and you’re new PHP template system is complete!

Published by Michael Boguslavskiy

Michael Boguslavskiy is a full-stack developer & online presence consultant based out of New York City. He's been offering freelance marketing & development services for over a decade. He currently manages Rapid Purple - and online webmaster resources center; and Media Explode - a full service marketing agency.

Join the Conversation

1 Comment

Leave a comment

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