PHP – Header and Footer Templates
Tuesday, August 25th, 2009So first let’s answer the question of why you’d want to use a header or footer template in your website. Luckily there is a very simple answer to that one. When you need to change a piece of navigation, or an image such as your logo, or even just change the copyright year in your footer, do you want to have to go into every HTML file to change that one item? Of course not! Using a php header and footer will allow you to avoid changing all of your pages, and instead only make you change it once!
So how does it work? Simple. There are a few catches though first which you might not like, so pay attention! First, your website URLs will now end in .php instead of .html. Second, you won’t be able to test your website without using a server that can compile your PHP. As I explained in a previous post, PHP – What Is It Good For?, PHP is a server side language, as opposed to HTML, CSS, or Javascript, which are all client side languages. Client side languages are read and interpreted by an individual person’s browser, whereas server side languages are read and interpreted by the server that hosts the website before it arrives back to the individual user. Easy solutions are to either put it up live to test it (not advised), or to install an Apache server on your computer, which wasn’t the easiest thing for me to do (because I’m not very techy) but there are some good walk-throughs out there, and the software is free. I use it all the time now because I do all my sites in PHP.
Now before I explain how to use this PHP, don’t be intimidated if you aren’t a programmer. Writing websites in php can be as little as 1% PHP and 99% HTML/CSS. I didn’t realize this until I actually tried to learn it, at which point I was much more comforted. You still make your entire site using your HTML or CSS, the PHP just decides essentially what content to put in where after you’ve made it all using your HTML/CSS.
Alright, now here is your explanation. You’ll need 3 total files. One called “header.php”, one called “footer.php”, and one called “index.php”. Inside your header file, cut and paste all the header code (starting all the way at your opening html tag or doctype declaration if you have one… because you should). Then, do the same for your footer file with your footer HTML. Now, inside of your index.php file write two lines of code, one at the top, and one at the bottom, you can probably guess which goes where:
<?php include(“footer.php”); ?>
And that’s it, run it on a server and you are set. Still a little confused? Well here, this is what each of your files should look like:
header.php
<body>
<div class="header">
Logo, navigation, et cetera goes in here
</div>
index.php
<div class="mainContent"> <h1>Header in here</h1> <p>Paragraph in here</p> </div>
<?php include(“footer.php”); ?>
footer.php
<div class="footer">
Footer content goes in here
</div>
</body>
</html>
And that’s it, got any questions, ask away!