Having to change 50 different pages to fix a link in your menu or adding a menu item in your footer can be quite a daunting task and quite frankly, not something you will want to do often. Using includes is a simple method of removing common parts of your code into a separate file [...]

Simplify your code with includes

By Karinne Legault | November 1st, 2007 |
Print This Article


Having to change 50 different pages to fix a link in your menu or adding a menu item in your footer can be quite a daunting task and quite frankly, not something you will want to do often. Using includes is a simple method of removing common parts of your code into a separate file and including them where you need it. It’s very simple to implement and you’ll be left wondering why you didn’t think of this when you were coding that big site.

There are two methods: PHP includes and SSI/ASP includes. Both are very similar except for the syntax of course.

PHP Includes

The best option is to use the PHP include() function.

The Syntax

<?php include('directory/file.php'); ?>

How to use it

Here’s your index.php file (note that all your files using the php include() function must have the .php extension)

...
<body>
<?php include('navigation.inc'); ?>
<div id="content">....</div>
</body>

And this would be your navigation.inc file (note that your included file can have the extension you want – .html, .php, .inc, .whatever)

<ul>
<li><a href="home.php">Home</a></li>
<li><a href="services.php">Services</a></li>
<li><a href="contact.php">Contact</a></li>
</ul>

SSI and ASP

There’s is also the SSI version (Server-Side Includes). It is also the same syntax for ASP includes

The Syntax

Using a virtual path (most commonly used)

<!––#include virtual="/directory/page.html" ––>

Using a relative path

<!––#include file="page.html" ––>

How to use

Here’s your index.shtml or index.asp file (note that all your files using the SSI or ASP include function must have either the .shtml or .asp extension)

...
<body>
<!––#include virtual="/navigation.inc" ––>
<div id="content">....</div>
</body>

And this would be your navigation.inc file (note that your included file can have the extension you want - .html, .asp, .inc, .whatever)

<ul>
<li><a href="home.shtml">Home</a></li>
<li><a href="services.shtml">Services</a></li>
<li><a href="contact.shtml">Contact</a></li>
</ul>

About The Author

Article By: Karinne Legault
Karinne Legault

Karinne Legault has 10 years of experience in the Web Design industry. You can see her portfolio at karinnelegault.com and her blog at karinne.net.

You can view other posts by Karinne Legault. Or you can visit Karinne's website at: http://www.karinnelegault.com/

Do you have something to say?