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

Google Buzz

Overview:
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”); ?>

Steps:
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.

Example:
The nav.php file:

1
2
3
4
<p id="fromMenuPhpFile"> <a href="home.php">Home</a> |
<a href="about.php">About Us</a> |
<a href="portfolio.php">Portfolio</a> |
<a href="contact.php">Contact Us</a>

The homepage.php:

1
2
3
&lt;?php include("nav.php"); ?&gt;
<h1>Welcome to my home page</h1>
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.

Download

phpNav.zip

  • del.icio.us
  • Digg
  • email
  • Facebook
  • FriendFeed
  • Google Bookmarks
  • Hexosearch
  • LinkedIn
  • Mixx
  • Print
  • PDF
  • StumbleUpon
  • Technorati
  • Twitter
  • RSS
This entry was posted in tutorial and tagged , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

One Comment

  1. RgCode
    Posted 23 February 2010 at 5:02 pm | Permalink

    thnx ….. you helped me alot :)

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>