Include Pages in PHP by AB

PHP is a powerful web language that has replaced HTML frames and JavaScript includes in performing the task of including code from one page onto another.

This is useful to include anything from a header, footer, menu or even a script across multiple pages. If you need to make a change to the header, footer, menu or script, then only one edit is needed.

Step 1

Step 1 is to create the page you want to have included.

You don't need to know PHP code for this step, just HTML. So, create a new page containing only the HTML code that you want to have included in other pages.

One important thing to note is to rename your page to something.php, and not .html as usual

The code just needs to be a snippet, so you don't need to add head or body tags if you are not specially including those tags. Below is an example of a menu in HTML:

<ul class="menu">
<li><a href="articles.php">Articles</a></li>
<li><a href="pictures.php">Pictures</a></li>
<li><a href="contact.php">Contact</a></li>
</ul>

Call it menu.php

Step 2

Step 2 is to create the page that you want to include the first page in. Also name this page something.php

Let's say your first page is just the menu and the second is your contact page. In your contact.php page, which is just plain HTML despite the name, leave a few blank lines for where the menu should go.

Step 3

This final step is how you include the first page with your snippet of HTML inside of your second HTML page.

Where you left that space for the menu, include this piece of code:

<?php include('menu.php'); ?>

Then save the file. As long as you have the correct path to your menu.php code this will work once you upload both pages to your PHP compatible server.

I don't suggest using the previous code since it relies on relative paths, and since you will want to use these page includes across your site you will want to use absolute paths.

To use absolute paths, use the following code where the first slash indicates starting from the domain name:

<?php include($DOCUMENT_ROOT . "/incudedfiles/menu.php"); ?>

To be efficient, you should make a folder where all your pages indended for including will go. Name the folder includes or incl or template or snippets or whatever you would like.