Layout with PHP Server-Side Includes

If you have a website containing more than a few pages ensuring that, for instance your menu system is up-to-date on every page can be very laborious and leave plenty of room for error. We used to use frames to cut out the hard work, until we realised has absolutely disastrous they were for the search engine indexing process.

With PHP you can use something called a server-side include to externalise generic regions of a design. To put it into simple terms, an include allows you to drop a portion of code (php, html, css, etc) anywhere into a document and then call it up when it’s needed.

Example:

Page 1

<html>

Top<br>

<?php include(“middle.php”) ?>

Bottom

</html>

middle.php

Middle<br>

Layout plan

To take this to an extreme, you can totally minimise the amount of repetive code within your source code by simply organising the code in the following way.

top.php

<html>
<head>
<title><?php echo $meta_title ?></title>
<meta name=”description” content=”<?php echo $meta_description?>”>
<meta name=”keywords” content=”<?php echo $meta_keywords ?>”>
</head>
<body>

menu.php

<a href=”page1.php”>Link 1</a><br>
<a href=”page2.php”>Link 2</a><br>
<a href=”page3.php”>Link 3</a><br>
<a href=”page4.php”>Link 4</a><br>

bottom.php

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

somepage.php (the actual page)

<?php
$meta_title = “This is my page”;
$meta_description = “Here is the description of this page”;
$meta_keywords = “server-side, include, php”;

include(“top.php”);
include(“menu.php”);
?>

 <p>The content goes here</p>

<?php include(“bottom.php”); ?>

 

It’s as simple as cutting a pasting the non unique parts of your page and placing them into separate documents. As long as you ensure that the page that is calling on the includes is point to the correct files and folders. Unfortunately, you can’t use absolute address:

You can’t use “/top.php”, or www.mywebsite.co.uk/top.php.
You can use “./top.php”, “top.php”, “../top.php”.

Search engine optmisation is always important, so make sure that any information unique to your page is kept on your page. This is why I have place the title and meta data into strings and defined them before the include (which contains the echo for each string).