I’m posting this because I thought that it might help some people who want to structurize their website in a way that they can easily edit pages which contain contents and pages which contain the code of the layout, as we separate layout code from contents in dynamic inclusion.
This is for PHP beginners, but I assume that you have basic knowledge about PHP variables and form submission methods if you would read this tutorial.
In this simple tutorial I’m writing, the content page will contain only contents. The layout is separated from contents, which makes updating the layout less complicated than if it were in the same file. Usually, I put the layout codes inside header.php and footer.php. Whenever I have to make changes to the layout, the only files I edit are those two.
An example
Let’s say that the following is your layout code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<html> <head> </head> <body> <table border="1"> <tr> <td> <a href="page1.php">page1</a> &nbsp; <a href="page2.php">page2</a> </td> </tr> <tr> <td style="background:pink;"> This is your website's homepage. </td> </tr> </table> </body> </html> |
Let’s consider the code of the table as the layout, and the text inside the second <td></td> tag is the content of your homepage.
We’ll be separating parts of that code and put them into separate .php files.
This chunk of code goes to header.php. You will notice that the links have changed. We’ll get to its explanation later.
1 2 3 4 5 6 7 8 9 10 11 12 |
<html> <head> </head> <body> <table border="1"> <tr> <td> <a href="index.php?page=page1.php">page1</a>&nbsp;<a href="index.php?page=page2.php">page2</a> </td> </tr> <tr> <td style="background:pink;"> |
The following goes to homepage.php
1 |
This is your website's homepage. |
This one goes to footer.php
1 2 3 4 5 |
</td> </tr> </table> </body> </html> |
Let’s create page1.php
1 |
You are viewing page1.php |
Let’s also create page2.php
1 |
You are viewing page2.php |
The following is your index.php and is a very important part because it’s the chunk of code which forms your website structure.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php include('header.php'); $x = $_GET['x']; if (!empty($x)) { include($x); } else { include('homepage.php'); } include('footer.php'); ?> |
Explanation of the modified links
The href attribute has the following value in our links in header.php
1 |
index.php?x=page1.php |
Here’s how it works. Using the get function, we assign to the variable $x on line 3 of index.php the name of the page we want to open, which is page1.php.
We have an if-else statement after the assignment. If variable $x is not empty, the page is included as the content. Or else, the homepage.php is included.
If we have another page, page3.php for example, then we would link to it using the following code:
1 |
<a href="index.php?x=page3.php">Go to page.php</a> |
I hope that helps.