PHP Menu Include function to reuse an html block on multiple pages

When making websites frequently we want a navigation bar or menu to show on every page. Rather than repeating the code on every single page, which is virtually impossible to update and maintain, or worse, using frames, use PHP to automate this and build each page dynamically. PHP will just paste in the navigation or whatever you’d want represented on every page. To do this we use the php include function. You can use include() to show headers, footers, or any elements that you’d reuse on multiple pages. The include() function takes all the text in a specified file and copies it into the file that calls the include function. This is great for scalability and updating- instead of changing multiple files, only change one!
Here’s what a php include function looks like:
<?php include(“nav.php”); ?>

1. Make the actual nav you want.

2. Put it into a php file (or any type of file, html, txt, as long as it’s formatted as html)

3. Place the php in your page to ‘print’ the desired file into your final html page before the browser renders the page using the include function. This spits out html. The viewer’s only see html, as that’s all it is, the php created the html file- That’s why it’s called PHP: Hypertext Preprocessor.

The nav.php file:
[cc lang=”php” tab_size=”2″ lines=”40″]

Home |
About Us |
Portfolio |
Contact Us


The homepage.php:
[cc lang=”php” tab_size=”2″ lines=”40″]
<?php include(“nav.php”); ?>

Welcome to my home page

home page text lorem ipsum

And here’s a sample site with a nav bar containing 4 pages included through php for Home, About, Portfolio and Contact.


3 thoughts on “PHP Menu Include function to reuse an html block on multiple pages

  1. And if we want to make the menu more dynamic, say, by making the current page unlinkable, then we just add a conditional statement like ‘if’ and check e.g. the title of the page. We could also change the menu in other ways depending on the current page.

    An example;
    Say I want the menu on my Poetry page. Since I set the title by using
    My Page –

    I can use $title, i.e. Poetry, which I also happen to call the page, poetry.html, to change the way PHP generates the menu. I haven’t actually done this yet so I won’t go into how, but it should be pretty simple.

Comments are closed.