Write a comment on this article
If you want to create a website without frames and each page should have the same header and footer, you will have to use the same code on each page. Imagine you want to change just a little bit of code, then you will have to make that change in all of your sites, maybe only ten, maybe hundreds. This will result in a lot of work.
With this tutorial we will minimize this effort. We won't create a "Content Management System" or a "Template Driven Website", but we will save a lot of time and work.
Some basic considerations: we want one main file (in this tutorial we use index.php) which loads the requested content dynamically. Header and footer will be always the same, the content may vary. This means, when the file index.php is called, the header file shall be loaded or included:
include("header.php");
The header file header.php is in the same directory as index.php and contains for example the title of the page and the navigation.
Now comes the most important part: loading the content. The content is separated in several files. To define which content will be displayed, we add a parameter to the URL called "load". In this parameter we pass which file should be loaded, like index.php?load=Home. If the parameter is not available, we use a default value.
if(!isset($_GET["load"])){
$_GET["load"] = "Home";
}
Before including the content file, we check if the file is available at all as the user can change the parameter to any value. If the file is not available, we display (include) an error.
if(file_exists($_GET["load"].".php")){
include($_GET["load"].".php");
}else{
include("error404.php");
}
In any case, afterwards the footer should be appended.
include("footer.php");
That's it! Our little templated page is ready to go. You could insert a navigation containing links calling index.php with a different parameter "load". This could look like this:
<a href="index.php?load=Home">Home</a> <a href="index.php?load=Contact">Contact</a> <a href="index.php?load=Archive">Archive</a>
In this case, you need to have 7 files in your directory:
You can try this script here: demos/Simple_template_usage/index.php?load=Home. Or download it here: Simple_template_usage_1-0.zip
PHP, tutorial, template, header, footer
If you have a question or a problem and you're looking for a solution, please use the forum. Comments might not be answered.