ยป Beginners Guide to PHP Includes
October 10th, 2008 | Filed in: Web Development | A lot of beginners to websites do the mistake to include all page elements on all the pages, making is hard to edit and very time consuming. Usually though, it’s because you don’t know what to do else. I remember the same when I first started out. So I’m going to go through how to divide a coded site into good sections using PHP includes, to ease everything for you later!
First lets describe the basic principle of PHP Includes, a principle that is pretty easy. Basically you put some content into one “reference” page (say we call it “sidebar.php”) and then using a simple code snippet, reference that page into another page; basically include the contents of that sidebar.php into your other file. When you need to update something in the sidebar, all you need to do is update that one PHP file, and the sidebar will update throughout the site.
Now, before we go into the code, I shall mention the only requirements here, and that’s that you have a server that will run PHP 4 or PHP 5 on it, otherwise this method is not going to work.
First off, we need to create a sample reference page. Let’s say that we want to include a sidebar into our index page. So we would need to create a page that I suggest you call “sidebar.php” and put in a folder called “includes”. That way you keep track on everything you include. In this page, you’ll use normal HTML formatting to outline your sidebar as you’d want it to look. Then on the page where you wish to include your sidebar, just type in the following code:
<?php include(“includes/sidebar.php”); ?>
If we break it down, it’s first opening the PHP tags, then opening an include function. After that we are telling it to find the file “sidebar.php” that is in the directory called “includes”.
NOTE: You could have any file ending really on the included page including regular .html extensions.
Remember to now save this page where we typed in the include as pagename.php. It’s very important that you use the .php extension or else the file will not parse the php include code on the page.
Taking it a step further: As I’m sure you’ve realized, this is not only good for sidebars, but headers, footers and every site element that will always be repeated on a page without changes that are page specific.
This include system is useful for certain elements. If you have on the other hand a lot of pages there is another system that could be more useful, that will prevent the need to include these elements on all pages. We’ll take a look at that in another tutorial. Basically, use this system to include any repeating objects that aren’t page specific, like sidebars, footers and headers. If you have a lot of content, use the other system!
Please leave a comment or make a trackback from your own site.














