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.

Related Posts:

Posts that may be related to "PHP: Dynamic inclusion tutorial":

Catzie

A Filipino programmer with a variety of interests such as baking, singing, making up silly song/rap lyrics, K-pop, drawing, creating unique dessert flavors, obsessing about finding out how some things works, board games, anime, video games, and forgetting things that usually go in her long list of interests. Running small-time online dessert shops Cookies PH and Catzie's Cakery.

Leave a Reply

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