Learning includes was an eye-opener for me. The idea is simple, but can really be a time-saver. This tutorial will show you how to use includes.
Let's imagine we have a 5 page website with our primary navigation on top. Traditionally, anytime we want to change an address, or add another link to our navigation, we must make the change on all 5 pages. With includes, we only have to make the changes on 1 file and the entire site will change. Here's how:
Lets take this html page for example. We will call this home.php:
PHP Code:
<!-- This file is home.php -->
<html>
<head><title>Includes are great!</title>
</head>
<body>
<!-- primary navigation -->
<a href="home.php">home</a>
<a href="faq.php">faq</a>
<a href="about_us.php">about_us</a>
<a href="contact.php">contact</a>
<a href="links.php">links</a>
<br><br>
Information for the home page here ....
</body>
</html>
All 5 pages of our site might have the exact same code above "Information for the home page here ..." This is the part that gets pretty time consuming if you have to edit all 5 pages each time you make a change to the navigation.
Now we will take all the redundant information and put it into a file called head.inc .
PHP Code:
<!-- This file is head.inc -->
<html>
<head><title>Includes are great!</title>
</head>
<body>
<!-- primary navigation -->
<a href="home.php">home</a>
<a href="faq.php">faq</a>
<a href="about_us.php">about_us</a>
<a href="contact.php">contact</a>
<a href="links.php">links</a>
<br><br>
Now that we have all the repeated information in a file named head.inc, we can re-code home.php with much less code. Below is an example of the new home.php:
PHP Code:
<?
// <- 2 slashes means this is a comment line
// first include the head.inc file
include("head.inc");
?>
Information for the home page here ....
</body>
</html>
Just to make it perfectly clear, below is an example of faq.php:
PHP Code:
<?
// <- 2 slashes means this is a comment line
// first include the head.inc file
include("head.inc");
?>
Information for the home faq here ....
</body>
</html>
Now if you wanted to add anything or edit the primary navigation, all you need to do is edit the 1 file called head.inc .
--------------------
With the above information, you should be on your way.. but I will explain one more thing now.
If the included file, head.inc, has php script inside of it, you must put the <? and ?> tags around any php code. For example, if I wrote the navigation in PHP instead of html, head.inc would like like this:
PHP Code:
<?
echo "<!-- This file is head.inc -->
<html>
<head><title>Includes are great!</title>
</head>
<body>
<!-- primary navigation -->
<a href=\"home.php\">home</a>
<a href=\"faq.php\">faq</a>
<a href=\"about_us.php\">about_us</a>
<a href=\"contact.php\">contact</a>
<a href=\"links.php\">links</a>
<br><br>";
?>
Now I'm using the echo command to print the text to the browser. Notice I HAVE to use the <? and ?> tags if I am using PHP within my included file.