Synook

Output buffering and static content inclusion - PHP

When I started making this site, I was thinking up of a new way to make the inclusion system for including (i.e. through include()) the static header and footer’s HTML for each dynamic page that was displayed.

The problem was, I couldn’t go by my old way of include("header"); include("content"); include("footer"), because I wanted a variable title for each content page, and the only place to set that was in the content file, but it needed to be echoed in the header’s markup.

The solution, I found, was to use output buffering to first include and store the contents of the content file, then include the header file, which read the $page_title, before displaying the buffered content.

<?php
  $page = urlencode($_GET['p']);
  include("config.php");
  ob_start();
  include("$page.php");
  $page = ob_get_contents();
  ob_end_clean();
  include("header.php");
  echo $page;
  include("footer.php");
?>

Simple, and in this way any variables that need to be set can be done so in the $page file, before being passed to header.php.