PHP Dynamic Includes
You learned in PHP Includes a very easy way of changing the layout of your site. Now what about the contents? If you thought the earlier tutorial was useful, wait until you read this.
A lot of people have been emailing me on how to make links look like this: site.php?page=support. And now, the answer to what you've been waiting for is now here. Let's start!
Step 1: Organize!
I don't like clutter so I place all the contents in a different directory called files. To make it easier to understand, here's how the directory looks like...

This is just to give you an idea on how my directories look like. For the purpose of this tutorial, I only included the files that we'll need.
You're already familiar with header.txt, footer.txt and index.php. In this tutorial, we have 3 new friends: the files directory and the files in it - home.txt and test.txt. You will meet them all soon enough.
Step 2: The Code
This is how our index.php should look like. Pay attention now...
<?php // THIS WAS EXPLAINED IN PHP Includes include ("header.txt"); // GETS VALUE FOR $page $page = strip_tags($_GET['page']); // SEES IF $page IS DEFINED // IF IT ISN'T IT WILL DISPLAY home.txt if (!$page) { $include = 'files/home.txt'; include ($include); } else { // $include ADDS THE DIRECTORY AND PAGE EXTENSION OF page $include = 'files/'.$page.'.txt'; // CHECKS IF $include EXISTS if (is_file("$include")) { // SHOWS THE CONTENT OF $include include ($include); } // DISPLAY ERROR MESSAGE IF $include IS NOT FOUND else { echo "The page you were trying to access is not found on this server."; } } // THIS WAS EXPLAINED IN PHP Includes include ("footer.txt"); ?>
Comments are placed to explain each part of the code to make it easier for you to understand. To explain how this code works further, here are some examples to illustrate...
If only index.php is typed in, it will display home.txt. If index.php?page=test is typed in, it will display test.txt. If there was a typographical error and index.php?page=tets was typed in, it will display the error message.
Got it? In the example above, just save the contents of your site as a .txt file and put them in the files directory.
Note that your files don't have to be in the files directory and saved as .txt. I just used that as an example. You can save your files with any extension and on any directory. If you are going to save them on a different directory or extension, just change this part of the code:
// $include ADDS THE DIRECTORY AND PAGE EXTENSION OF page $include = 'files/'.$page.'.txt';
Just change the files to the directory you saved your file to and txt to the extension of your file.
Conclusion
Wasn't that easy? This makes it very convenient, doesn't it? It also makes the loading time faster. You may download the files in this tutorial here. Enjoy!
If you have any questions or if you want to discuss this tutorial, you may post at Blinding Light MB.