Easy Menus with PHP, Part 2

Yesterday I discussed the limited options for efficient menu-editing available to beginning Web programmers. As promised, here’s a tutorial for writing your very own PHP includes, a boon to menu-making code monkeys. If you haven’t already, please check out my mini PHP crash course before continuing.

Using the include() statement (and it’s partner require() ) lets you plop a chunk of PHP code in the middle of your HTML or PHP page, like this:

Code:

<!-- HTML here -->
<?php
// horizontal menu (this is a PHP comment)
include('menu.php');   // "include the file 'menu.php' right here in the webpage"
?>
<!-- more HTML -->
SciTE Screenshot: This is a code editor I use. It works for (X)HTML, PHP, and much more.

SciTE Screenshot: This is a code editor I use. It works for (X)HTML, PHP, and much more.

Here’s the gist:

  • Open a text file or text-based HTML editor such as SciTE. You  need to be editing the source (as opposed to the page’s visual content).
  • Insert the PHP code above into where you want the menu to appear. Note:
    • The file can have any name, as well, such as  1header.htm, as long as you use that filename in the PHP code.
    • The included file can be another extension, such as menu.htm . It just may be easier to make it .PHP to start with, in case you want to make yet another include inside of that one.
    • You can use pretty much as many includes and requires as you want, though trying to load hundreds could make the system choke. It times out after about 30 seconds, cutting off your webpage at that point.  (Don’t worry, this probably won’t happen unless you’re a code monkey like me who wants, say, to display all hundred-plus menu category pages from the local chamber of commerce website, all on one page. Didn’t work out so well.)
  • Save the file as .PHP (not .HTM or .HTML).
  • You’re all done, lickety-split. Congrats!
  • Now you just have to do the same thing with all your webpages.

“What?” you say. “I thought you were making it so we didn’t have to manually update every webpage each time we want to change the menu!” Yes, but you have to set the framework first. Just make a plan at the beginning — ideally before you even begin coding your website — and it will make your work go much more smoothly. Whenever you want to change the menu, just update menu.php and the whole site changes to match. Voila’! Instant webpage-menu-updating goodness.

Leave a Reply

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