Server Side Includes – SSI: include() and require() functions

A Server Side Include is any piece of code which can be included on multiple pages to make the code more modular and reusable. E.g: If you have a website of 10 pages and all the pages have the same header and footer, then we can separate the header code in header.php and footer code in footer.php. header.php and footer.php are now called “Server Side Included”.

Now that we have our SSI’s ready we need to include them in all the 10 pages. This can be achieved by using include() or require() functions. Both these functions essentially do the same thing – that is include a piece of code in a PHP file before it is executed by the server. Let’s look at this with some examples:

header.php

<?php echo “I am a header\n”; ?>

footer.php

<?php echo “I am a footer\n”; ?>

body.php

<html>
<head>
</head>
<body>

<?php
include(“header.php”); OR require(“header.php”);
echo “I am a body\n”;
include(“footer.php”); OR require(“footer.php”);
?>

</body>
</html>

Output: When you goto the body.php page – http://www.mydomain.com/body.php – you should see this output.

I am a header
I am a body
I am a footer

So both include() and require() functions do the same thing. The only thing they differ in, is the way they handle errors. If there is any error in the file included using include() function, then you will see a warning on the body.php page but the entire code of body.php page after the include() function will still be executed.

However, if there is an error in the files you are including using a require() function, you will see FATAL error reported on the body.php page and the execution STOPS right after require() function. So no code after require() function from body.php will be executed.

Advantages: Here are a few advantages of using SSI’s:

  1. Code becomes more modular.
  2. Easy to maintain code. You only need to change the code in one location.
  3. You can sometimes achieve parallel development. If one engineer is developing the header someone else can start working on the body.