PHP: Dynamic Includes

Please be aware that dynamic PHP includes are not as secure/safe as PHP includes. If you are following this tutorial, your files should all be in the same folder, not in subfolders.

You will need to have several files ready: index.php, index2.php and page.php.


In this page, add your layout as you would normally, with the stylesheet, divs, and perhaps the sidebar. You will naturally have a space for the blog or updates – basically, the home page. If an incorrect URL is typed, the user will be redirected here.

This will be the part of the page that “changes”. In that part of the page, place the following code:

<?php if (isset($_GET['x'])) {
   if (strpos($_GET['x'], "/")) {
      $dir = substr(str_replace('..', '', $_GET['x']), 0, strpos($_GET['x'], "/")) . "/";
      $file = substr(strrchr($_GET['x'], "/"), 1);
      if (file_exists($dir.$file.".php")) {
      } else {
   } else {
      if (file_exists(basename($_GET['x']).".php")) {
      } else {
} else {
} ?>

By placing that in the page, index2.php will display in your layout by default when you visit index.php.


This is the page where you place your blog or welcome message. You do not need to place your layout here. You simply place the content on your homepage.


Imagine that this is a page in your website. Simply place some text here – about yourself, or your website. Again, you do not need to place your layout here. Just place text, with the regular header styling, bold styling, images, and so on.

Creating Links and Pages

The links need to be in this format:

<a href="index.php?x=page">this is a link</a>

The text page is obviously the name of the page (without the .php extension). You can place this link anywhere. It can be on your sidebar in index.php, or it can be inside the pages, such as in your blog, if you want to link to that page directly from there.

To create more pages, just create a regular .php page – such as page2.php or page3.php. Simply write formatted text inside those pages; the content that will appear in your page. Remember, you don’t need to put the layout here at all.

That’s about all there is to dynamic PHP includes. If you need to change your layout, you just have to edit around index.php without removing the vital code. To edit your other pages, you just find the name of the page and edit it.

Make sure all of these files are uploaded to the same folder.