Let’s say you had a website with two pages and a navigation bar on each page. Now assume that you have to change this navigation bar. The basic way to do this would be to go into each file and change the HTML markup.

With just two pages, this isn’t much of a hassle. But what about five pages? How about 20? 100? As you can see, this method is just unreasonable as your website increases in size.

Many web developers solve this problem with PHP includes. PHP is a server-side scripting language whose files can contain HTML markup and the ability of using PHP:

<?php
// php code is placed here
?>

Looking back at the problem, we need a way to change the navigation bar on all the files efficiently. Because we will be using PHP, all the files need to be changed to a .php extension. Once this is completed, we can look at the PHP include_once function.

This function enables the inclusion of a PHP file. Inclusion means that the code in the included file is added directly into the current file by the server. This enables us to create one file with our navigation in it and just include it from all our actual pages.

Now for our PHP file containing the navigation bar. We will call this navbar.php:

<div id="navigation">
     <ul>
          <li><a href="#">First Page</a></li>
          <li><a href="#">Second Page</a></li>
          <li><a href="#">Third Page</a></li>
    </ul>
</div>

Notice that this is all HTML markup. This is completely valid, because a PHP file is allowed to contain HTML.

Let’s move on to our actual pages. Instead of writing out the above code wherever we want the navigation bar, we can just place this line in instead:

<?php include_once("navbar.php"); ?>

Now that we have this system in place, we can effortlessly solve our problem. If we wanted to add in a forth page to our navigation bar, all we would have to do is change navbar.php:

<div id="navigation">
     <ul>
          <li><a href="#">First Page</a></li>
          <li><a href="#">Second Page</a></li>
          <li><a href="#">Third Page</a></li>
          <li><a href="#">Fourth Page</a></li>
    </ul>
</div>

and all our pages would experience this change because they include the code in this file.

Once you first use the efficiency PHP gives you, it’s hard to switch to any other server-side scripting language.

Leave a Reply

PHP Includes