PHP: Dynamic inclusion tutorial

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:

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.

The following goes to homepage.php

This one goes to footer.php

Let’s create page1.php

Let’s also create 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.

Explanation of the modified links

The href attribute has the following value in our links in header.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:

I hope that helps.

Catzie

A Filipino programmer and baker. When I have time to spare, I blog, play video games, watch series (usually anime), cook dishes, draw, or spend a little time with pets. When I have the rare luxury of time, I get to travel and record song covers too! Baked-Per-Order Sweets: Catzie's Cakery Follow on Twitter: @catzie

Leave a Reply

Your email address will not be published. Required fields are marked *