The Use Of Includes (PHP)
Monday, May 28th, 2007It’s a very basic concept but often omitted, making life much more difficult than need be.
A basic principle that I follow is to never repeat identical code. If you have to repeat identical code somewhere, you should use an include, which will save you a lot of time and effort.
So, what is an include? It is a file that has a portion of text that you plan on using repeatedly throughout your site. For instance, the footer of your site that contains perhaps a few navigation links and your copyright is a great idea for an include. Lets say you have a very basic page, something like this:
You can put that bottom copyright into a file, lets say footer.php (all my files are php, you can use any extension, .htm, .html, etc).
Now, to make this more interesting, lets say we added in some navigation at the bottom:
To include this file (remember that I’m using PHP, there are alternate methods in other scripting languages), your original page would now look like this:
This puts all the code in footer.php right in that page. No visitor can see your php code – in this case it gets replaced by the code in the file, so it looks like a completely normal page. This enables you to put that little php include at the bottom of all your pages, and they all use the same page, so you never have to repeat that code. Now, if you change something in footer.php it will change that code on every page in your site. Most of my pages look something like this:
I removed a little bit of code from my website that has more advanced features. If you want to learn about those, let me know.-Kerry
