Using Includes

There are a handful of PHP statements that can be used to import scripts from files other than the one currently being interpreted. This, for example, allows you to divide the production of a page into its constituent parts. The header and footer listings here should be placed in a folder in your htdocs called templates.

header.inc

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>The Template Machine</title>
</head>
<body>

footer.inc

<p>The bottom of the page.</p>
</body>
</html>

The PHP file should be placed in htdocs, NOT in the same folder as the includes. Call it what you like, but remember it needs a .php extension.

<?php
require("templates/header.inc");

// Main page content here
echo "<h1>Main Page Here</h1>\n
<p>And some stuff.</p>\n";
// End of main page

require("templates/footer.inc");
?>

In this example, the require statement has been used. This statement causes an error if the file mentioned does not exist. An alternative statement, include, does not cause an error if it fails to find the file. In this example, the included files contain HTML. If PHP is used in the included files, you need to enclose it in <?php ... ?> tags.

This web site uses lots of includes. Different parts of the pages are stored in separate files. PHP scripts stitch together all of these things to make a page. Bear in mind that the same list of links appears on every page in a section of the site. Being able to edit that information in a single place is useful.